线程同步互斥中信号量的使用
// 线程同步之信号量(注意和IPC信号量的区别,IPC信号量用于进程间通信)
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
using namespace std;
// 信号量
sem_t sem;
// 公共缓冲区,给生产者和消费者读写
char common_buffer[64];
// 生产者线程
void* producer(void* data)
{
int count = 0;
while(count < 64)
{
++count;
// 往缓冲区中填充数据
sprintf(common_buffer,"%d",count);
// 激活信号量,即P操作
sem_post(&sem);
sleep(1);
}
}
// 消费者线程
void* consumer(void* data)
{
int count = 0;
while(count < 64)
{
// 等待信号量的值变成1,即V操作
sem_wait(&sem);
// 消耗数据
printf("%s\n",common_buffer);
++count;
}
}
// 主函数
int main(int argc,char* argv[])
{
// 初始化信号量
sem_init(&sem,0,0);
// 定义两个线程id
pthread_t thd1,thd2;
// 创建生产者和消费者线程
pthread_create(&thd1,0,consumer,0);
pthread_create(&thd2,0,producer,0);
// 等待两个线程运行结束
pthread_join(thd1,0);
pthread_join(thd2,0);
// 销毁信号量
sem_destroy(&sem);
return 0;
}