Jiwu Bu

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  32 随笔 :: 0 文章 :: 25 评论 :: 0 Trackbacks
使用信号量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)
{
    
whiletrue )
    {
        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)
{
    
whiletrue )
    {
        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, 00!= 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

posted on 2009-11-17 13:28 bujiwu 阅读(575) 评论(0)  编辑 收藏 引用 所属分类: Linux

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理