使用信号量sem_t实现生产者与消费者实例。主要用到以下几个函数:
sem_init()
sem_destroy()
sem_post()
sem_wait()
//g++ -o semaphore semaphore.cpp -lpthread
#include <semaphore.h>
#include <errno.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "ThreadMutex.h"
#define MAXSIZE 10
sem_t g_sem_max;
sem_t g_sem_zero;
CThreadMutex g_mutex;
int g_count = 0;
int sem_wait_i(sem_t* psem)
{
int rv = 0;
while ( 0 != ( rv = sem_wait(psem) ) )
{
if ( errno == EINTR )
{
continue;
}
else
{
printf("sem_wait %s\n", strerror(errno) );
break;
}
}
return rv;
}
void* producer_thread(void* Parameter)
{
while( true )
{
sleep(2);
if( sem_wait_i(&g_sem_max) != 0 )
{
break;
}
g_mutex.Lock();
g_count++;
printf("Producer=%d\n", g_count);
sem_post(&g_sem_zero);
g_mutex.UnLock();
}
return NULL;
}
void* consumer_thread(void* Parameter)
{
while( true )
{
sleep(3);
if( sem_wait_i(&g_sem_zero) != 0 )
{
break;
}
g_mutex.Lock();
g_count--;
printf("Consumer=%d\n", g_count);
sem_post(&g_sem_max);
g_mutex.UnLock();
}
return NULL;
}
int main(int argc, char* argv[])
{
if ( sem_init(&g_sem_zero, 0, 0) != 0 )
{
printf("sem_init %s\n", strerror(errno) );
return -1;
}
if ( sem_init(&g_sem_max, 0, MAXSIZE) != 0 )
{
printf("sem_init %s\n", strerror(errno) );
return -1;
}
pthread_t pro_thread;
pthread_t sum_thread;
if ( pthread_create( &sum_thread, NULL, consumer_thread, NULL) != 0 )
{
printf("pthread_create%s\n", strerror(errno) );
return -1;
}
if ( pthread_create( &pro_thread, NULL, producer_thread, NULL) != 0 )
{
printf("pthread_create%s\n", strerror(errno) );
return -1;
}
if ( pthread_join(pro_thread, NULL) != 0 )
{
printf("pthread_join %s\n", strerror(errno) );
return -1;
}
if ( pthread_join(sum_thread, NULL) != 0 )
{
printf("pthread_join %s\n", strerror(errno) );
return -1;
}
sem_destroy(&g_sem_zero);
sem_destroy(&g_sem_max);
return 0;
}
http://www.cppblog.com/Files/bujiwu/semaphore.rar