本文提供一个用信号量对线程实现闭环控制的程序,该程序只是为了演示信号量的作用,并没有实用价值。
程序的逻辑很简单,类似于数字电路中的时序图。在main()中触发一下,程序就会进入闭环控制了。上个图就一目了然了。
代码如下:
#include
#include
#include
sem_t sem1,sem2,sem3;
void *thread_a(void*in)
{
while(1)
{
sem_wait(&sem1);
printf("Thread_a run\n");
sem_post(&sem2);//增加信号sem2,让thread_b可以运行
}
}
void *thread_b(void*in)
{
while(1)
{
sem_wait(&sem2);//sem2=0时阻塞,等待同步信号
printf("Thread_b run\n");
sem_post(&sem3);//增加信号sem3,让thread_c可以运行
}
}
void *thread_c(void*in)
{
while(1)
{
sem_wait(&sem3);//sem1=0时阻塞,等待同步信号sem1
printf("Thread_c run\n\n");
sleep(1);
sem_post(&sem1);//增加信号sem1,让thread_a可以运行
}
}
int main(int argc,char **argv)
{
pthread_t a,b,c;
sem_init(&sem1,0,0);//初始化信号量
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
//创建3个子线程
pthread_create(&a,NULL,thread_a,NULL);
pthread_create(&b,NULL,thread_b,NULL);
pthread_create(&c,NULL,thread_c,NULL);
sem_post(&sem1);//触发
/*执行到此处时,进程中共有四个线程,用信号量来控制四个线程执行的顺序*/
pthread_join(a,NULL);
pthread_join(b,NULL);
pthread_join(c,NULL);
//释放信号量资源
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
return 0;
}