linux 调度精度,Linux mutithreaded C程序<-> usleep()每小时间隔的调度精度

您可以在SIGALRM处理程序中将setitimer()与self-pipe trick结合使用。应定期调度的线程必须在管道的读取端执行阻塞read()。

看到这个玩具的使用示例展示了主意:

#define _POSIX_C_SOURCE 200101L

#define _BSD_SOURCE

#include

#include

#include

#include

#include

#include

int pipefd[2];

const char pipechar = 'x';

void *periodicThread(void *arg)

{

(void)arg; // unused

char c;

while (read(pipefd[0], &c, 1) > 0)

{

if (c == 'q') break;

puts("scheduled!");

}

return 0;

}

void alarmHandler(int signum)

{

(void)signum; // unused

write(pipefd[1], &pipechar, 1);

}

int main(void)

{

if (pipe(pipefd) < 0) return 1;

int rc = 1;

pthread_t thread;

if (pthread_create(&thread, 0, periodicThread, 0) != 0)

goto cleanup_pipe;

struct sigaction sa = {

.sa_handler = alarmHandler,

.sa_flags = SA_RESTART // aternatively check for EINTR after avery system call

};

if (sigaction(SIGALRM, &sa, 0) < 0) goto cleanup_thread;

// use (much) larger values here!

struct itimerval itv = {

.it_interval = {

.tv_sec = 5,

.tv_usec = 0

},

.it_value = {

.tv_sec = 5,

.tv_usec = 0

}

};

if (setitimer(ITIMER_REAL, &itv, 0) < 0) goto cleanup_thread;

rc = 0;

int c;

while ((c = getchar()) != EOF)

{

if (c == 'q') break;

}

const char pipeendchar = 'q';

cleanup_thread:

write(pipefd[1], &pipeendchar, 1);

pthread_join(thread, 0);

cleanup_pipe:

close(pipefd[0]);

close(pipefd[1]);

return rc;

}

如果你的月经变得很长,即使在struct itimerval的time_t领域,你可以选择一个更小的周期,只是计数的SITGALRM数你接收。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值