/***********************************
*Date:Thu Apr 10 17:51:36 CST 2014
*有名信号量在多线程中的使用
************************************/
#include <iostream>
extern "C"{
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <semaphore.h>
#include <pthread.h>
}
using namespace std;
#define SEM_MUTEX "sem_mutex"
#define SEM_NEMPTY "sem_empty"
#define SEM_NSTORED "sem_stored"
#define NDATABUF 10
int data_buf[NDATABUF];
sem_t* sem_mutex = NULL;//锁
sem_t* sem_nempty = NULL;//是否空
sem_t* sem_nstored = NULL;//是否可以存
int init()
{
sem_mutex = sem_open(SEM_MUTEX,O_CREAT|O_RDWR,0666,1);
if(sem_mutex == SEM_FAILED){
cerr << "failed to open mutex sem,error:" << strerror(errno) << endl;
return -1;
}
sem_nempty = sem_open(SEM_NEMPTY,O_CREAT|O_RDWR,0666,NDATABUF);//初始化,数组是空的,均未存数据
if(sem_nempty == SEM_FAILED){
cerr << "failed to open empty sem,error:" << strerror(errno) << endl;
return -1;
}
sem_nstored = sem_open(SEM_NSTORED,O_CREAT|O_RDWR,0666,0);
if(sem_nstored == SEM_FAILED){
cerr << "failed to open stored sem,error:" << strerror(errno) << endl;
return -1;
}
return 0;
}
void destroy()
{
sem_unlink(SEM_MUTEX);
sem_unlink(SEM_NEMPTY);
sem_unlink(SEM_NSTORED);
}
//生产者线程
void* produce(void* arg)
{
int iNempty,iNstored,iMutex;
for(int i = 0;i < NDATABUF;i++){
sem_wait(sem_nempty);//有空间存数据
sem_wait(sem_mutex);//锁住临界区
data_buf[i] = i+1;
#ifdef _DEBUG
sem_getvalue(sem_nempty,&iNempty);
sem_getvalue(sem_nstored,&iNstored);
sem_getvalue(sem_mutex,&iMutex);
cout << "produce->nempty:" << iNempty << ",nstored:" << iNstored << ",mutex:" << iMutex << endl;
#endif
sem_post(sem_mutex);//解锁
sem_post(sem_nstored);//唤醒线程有数据可取
}
return NULL;
}
//消费者线程
void* consume(void* arg)
{
int iNempty,iNstored,iMutex;
for(int i = 0;i < NDATABUF;i++){
sem_wait(sem_nstored);//有数据可取
sem_wait(sem_mutex);//锁住临界区
#ifdef _DEBUG
sem_getvalue(sem_nempty,&iNempty);
sem_getvalue(sem_nstored,&iNstored);
sem_getvalue(sem_mutex,&iMutex);
cout << "consume->nempty:" << iNempty << ",nstored:" << iNstored << ",mutex:" << iMutex << endl;
#endif
cout << data_buf[i] << endl;
sem_post(sem_mutex);//解锁
sem_post(sem_nempty);//通知有空间可以存
}
return NULL;
}
int main(int argc,char* argv[])
{
int res = init();
if(res == -1){
cerr << "failed to initialize semaphore" << endl;
destroy();
return -1;
}
pthread_t p1,p2;
res = pthread_create(&p1,NULL,produce,NULL);
if(res == -1){
cerr << "failed to create thread 1" << endl;
destroy();
return -1;
}
res = pthread_create(&p2,NULL,consume,NULL);
if(res == -1){
cerr << "failed to create thread 2" << endl;
destroy();
return -1;
}
//等待线程结束
pthread_join(p1,NULL);
pthread_join(p2,NULL);
destroy();
return 0;
}
Posix信号量实例
最新推荐文章于 2024-04-20 10:22:19 发布