您的位置:首页 > 其它

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

2018-02-26 15:12 246 查看
环境: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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐