使用两个信号量和全局变量实现多线程间同步通信

环境:linux vim

功能:使用两个信号量和全局变量实现多线程间同步通信

编译:gcc sem.c -o sem -lpthread

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>//exit
#include <string.h>
#include <pthread.h>//pthread_create() pthread_join() pthread_exit
#include <semaphore.h>//sem_t sem_init()


char buf[32];//global var to communicate within pthread
sem_t sem_r, sem_w;//两个信号量分别标记读资源 和 写资源
void *function(void * arg);//函数指针


int main()
{
pthread_t a_thread;
if(sem_init(&sem_r,0,0) < 0)
{
perror("sem_r init");
exit(-1);//进程结束
}
if(sem_init(&sem_w,0,1) < 0)
{
perror("sem_w init");
exit(-1);
}


if(pthread_create(&a_thread,NULL,function,NULL) != 0)
{
printf("fail to create pthread\n");
exit(-1);
}
printf("input quit to quit\n");
do{
sem_wait(&sem_w);
fgets(buf,32,stdin);
sem_post(&sem_r);
}while(strncmp(buf,"quit",4) != 0);


return 0;
}


void *function (void *arg)
{
while(1)
{
sem_wait(&sem_r);
printf("buf is :%s\n",buf);
sem_post(&sem_w);
}
}

猜你喜欢

转载自blog.csdn.net/qq_37051576/article/details/79377468