使用两个信号量和全局变量实现多线程间同步通信
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);
}
}
功能:使用两个信号量和全局变量实现多线程间同步通信
编译: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);
}
}
相关文章推荐
- 使用System V信号量实现多线程互斥
- 如何在不使用第三方变量的前提下,交换两个变量的值 (Java实现)
- 不使用第三方变量 给两个变量相互交换值PHP实现
- 算法研究之不使用临时变量实现两个值的交换
- 使用两个信号量实现主线程和线程池同步
- 如何统计网站访问量,代码实现使用全局变量 Application,start,end,Session_start,Session_end事件
- 不使用第三个变量,实现交换两个变量的值
- 在python中实现生产者和消费者的例子(四):使用thread模块和全局变量
- MATLAB GUI ,2,使用MATLAB的函数来实现MATLAB GUI,part 3,全局变量,计时器和状态机
- 多线程 - 使用Mutex和条件变量实现信号量
- 线程间无需特别的手段进行通信,因为线程间可以共享数据结构,也就是一个全局变量可以被两个线程同时使用,不过要注意的是线程间需要做好同步。
- [置顶] 如何统计网站访问量,代码实现使用全局变量 Application,start,end,Session_start,Session_end事件
- 不使用中间变量实现两个变量的交换
- 在python中实现生产者和消费者的例子(五):使用threading模块和全局变量
- 不使用第三个变量,实现两个变量值的交换
- 使用内存映象实现进程间全局变量
- 使用内存映象实现进程间全局变量
- 实现两个int变量的值的交换,要求不使用临时变量。
- 如何统计网站访问量,代码实现使用全局变量 Application,start,end,Session_start,Session_end事件
- 使用两个信号量实现主线程和线程池同步