【发布时间】:2019-12-15 13:26:23
【问题描述】:
我有以下代码sn-p:
#include <iostream>
#include <thread>
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/timerfd.h>
int main() {
std::thread rr_thread([](){
struct sched_param params = {5};
pthread_setschedparam(pthread_self(), SCHED_RR, ¶ms);
struct itimerspec ts;
struct epoll_event ev;
int tfd ,epfd;
ts.it_interval.tv_sec = 0;
ts.it_interval.tv_nsec = 0;
ts.it_value.tv_sec = 0;
ts.it_value.tv_nsec = 20000; // 50 kHz timer
tfd = timerfd_create(CLOCK_MONOTONIC, 0);
timerfd_settime(tfd, 0, &ts, NULL);
epfd = epoll_create(1);
ev.events = EPOLLIN;
epoll_ctl(epfd, EPOLL_CTL_ADD, tfd, &ev);
while (true) {
epoll_wait(epfd, &ev, 1, -1); // wait forever for the timer
read(tfd, &missed, sizeof(missed));
// Here i have a blocking function (dummy in this example) which
// takes on average 15ns to execute, less than the timer period anyways
func15ns();
}
});
rr_thread.join();
}
我有一个使用 SCHED_RR 策略的 posix 线程,在这个线程上有一个 POSIX 计时器正在运行,超时时间为 20000ns = 50KHz = 50000 滴答/秒。
定时器触发后,我正在执行一个比定时器周期少大约 15ns 的函数,但这并不重要。
当我执行此操作时,我得到 100% 的 CPU 使用率,整个系统变慢,但我不明白为什么会发生这种情况,而且有些事情令人困惑。
为什么 100% 的 CPU 使用率,因为线程应该在等待计时器触发时处于休眠状态,所以理论上可以安排其他任务,对吗?即使这是一个高优先级线程。
我使用 pidstat 检查了上下文切换的数量,它似乎非常小,接近 0,无论是自愿的还是非自愿的。这是正常的吗?在等待计时器触发调度程序时,应该安排其他任务吗?我应该看到至少 20000 * 2 上下文切换/秒
【问题讨论】:
-
50 kHz 对于计时器来说是非常核心的。如果您能得到它,那么您将花费大量时间对其进行维修。
-
@JohnBollinger 是的,对不起,我的错,来晚了,我会改变的
-
我不确定 50kHz 在大多数常见硬件上是否可行。计时器很可能“尽可能快”地关闭(因此 CPU 使用率为 100%),但不是每秒 50,000 次。
标签: c++ linux pthreads scheduled-tasks scheduler