我是靠谱客的博主 长情时光,最近开发中收集的这篇文章主要介绍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数你接收。

最后

以上就是长情时光为你收集整理的linux 调度精度,Linux mutithreaded C程序<-> usleep()每小时间隔的调度精度的全部内容,希望文章能够帮你解决linux 调度精度,Linux mutithreaded C程序<-> usleep()每小时间隔的调度精度所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(50)

评论列表共有 0 条评论

立即
投稿
返回
顶部