Linux编程题:创建3个线程分别打印abc,用信号量进行同步
创建三个线程,分别打印a,b,c。 现在要求用信号量对线程进行同步,无论程序运行多少次、如何运行,都能使整个程序依次打印 a b c a b c a b c . . . 一直死循环 同步过程如下图,需要三个信号量:代码如下(linux系统下):1 #include<stdio.h>2 #include<unistd.h>3 #include<...
·
创建三个线程,分别打印a,b,c。 现在要求用信号量对线程进行同步,无论程序运行多少次、如何运行,都能使整个程序依次打印 a b c a b c a b c . . . 一直死循环
同步过程如下图,需要三个信号量:
代码如下(linux系统下):
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#include<stdlib.h>
sem_t sem[3];
void* fun1(void* arg)
{
while(1)
{
sem_wait(&sem[0]);
write(1,"a",1);
sem_post(&sem[1]);
}
}
void* fun2(void* arg)
{
while(1)
{
sem_wait(&sem[1]);
write(1,"b",1);
sem_post(&sem[2]);
}
}
void* fun3(void* arg)
{
while(1)
{
sem_wait(&sem[2]);
write(1,"c",1);
sem_post(&sem[0]);
}
}
int main()
{
pthread_t id[3];
sem_init(&sem[0],0,1);
sem_init(&sem[1],0,0);
sem_init(&sem[2],0,0);
pthread_create(&id[0],NULL,fun1,NULL);
pthread_create(&id[1],NULL,fun2,NULL);
pthread_create(&id[2],NULL,fun3,NULL);
pthread_join(id[0],NULL);
pthread_join(id[1],NULL);
pthread_join(id[2],NULL);
sem_destroy(&sem[0]);
sem_destroy(&sem[1]);
sem_destroy(&sem[2]);
exit(0);
}
运行结果如下:
更多推荐
已为社区贡献1条内容
所有评论(0)