您的位置:首页 > 运维架构 > Linux

(原創) 如何让一个thread在背景不断的执行? (使用semaphore) (OS) (Linux) (C/C++) (C)

2006-12-04 01:02 1051 查看
要让一个thread在背景不断的执行,最简单的方式就是在该thread执行无穷回圈,如while(1) {},这种写法虽可行,却会让CPU飙高到100%,因为CPU一直死死的等,其实比较好的方法是,背景平时在Sleep状态,当前景呼叫背景时,背景马上被唤醒,执行该做的事,做完马上Sleep,等待前景呼叫。当背景sem_wait()时,就是马上处于Sleep状态,当前景sem_post()时,会马上换起背景执行,如此就可避免CPU 100%的情形了。

1#include <stdio.h> // printf(),
11#include <stdlib.h> // exit(), EXIT_SUCCESS
12#include <pthread.h> // pthread_create(), pthread_join()
13#include <semaphore.h> // sem_init()
14
15sem_t binSem;
16
17void* helloWorld(void* arg);
18
19
54void* helloWorld(void* arg) while(1) // Wait semaphore
57 sem_wait(&binSem);
58 printf("Hello World\n");
59 }
60}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: