pthread线程通信方式之信号量
张成
2016/6
#include <iostream> using namespace std; /** * pthread 同步 - 信号量控制 */ #include <unistd.h> #include <pthread.h> #include <semaphore.h> #define BUFFER_SIZE 4 #define OVER (-1) typedef struct producers { int buffer[BUFFER_SIZE]; int readpos,writepos; sem_t sem_read; sem_t sem_write; }producers; void init(producers *b) { sem_init(&b->sem_write,0,BUFFER_SIZE); sem_init(&b->sem_read,0,0); b->readpos=0; b->writepos=0; } void put(producers *b,int data) { sem_wait(&b->sem_write);//等待信号 b->buffer[b->writepos] = data; b->writepos++; if(b->writepos>=BUFFER_SIZE) b->writepos=0; sem_post(&b->readpos);//发射信号 } int get(producers *b) { int data; sem_wait(&b->sem_read); data = b->buffer[b->readpos]; b->readpos++; if(b->readpos>=BUFFER_SIZE) b->readpos=0; sem_post(&b->sem_write); return data; } producers buffer; void *producer(void* data) { int n; for(n=0;n<10;n++) { printf("Producer: %d --> \n",n); put(&buffer,n); } put(&buffer,OVER); return nullptr; } void* consumer(void* data) { int d; while(1) { d = get(&buffer); if(d == OVER) break; printf("Consumer:--> %d\n",d); } printf("Consumer线程退出\n"); return nullptr; } int main() { cout << "Hello, World!" << endl; pthread_t tha,thb; void *retval; init(&buffer); pthread_create(&tha,NULL,producer,0); pthread_create(&thb,NULL,consumer,0); pthread_join(tha,&retval); pthread_join(thb,&retval); return 0; }