知识屋:更实用的电脑技术知识网站
所在位置:首页 > 操作系统 > linux

Linux网络编程:生产者消费者问题

发布时间:2014-09-05 17:01:14作者:知识屋

From:
http://www.linuxidc.com/Linux/2011-08/41792.htm
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
 
void * producter_f(void *arg);
void * consumer_f(void *arg);
int buffer_has_item = 0;
sem_t sem;
int running = 1;
 
int main(void)
{
    pthread_t consumer_t;
    pthread_t producter_t;
   
    sem_init(&sem, 0, 16);
   
    pthread_create(&producter_t, 0, (void*)producter_f, 0);
    pthread_create(&consumer_t, 0, (void*)consumer_f, 0);
   
    sleep(1);
    running  = 0;
    pthread_join(consumer_t, 0);
    pthread_join(producter_t, 0);
   
    sem_destroy(&sem);
   
    return 0;
}
 
void * producter_f(void * arg)
{
    int semval = 0;
    while(running)
    {
        usleep(0);
        sem_post(&sem);
        sem_getvalue(&sem, &semval);
        printf("生产,总数量:%d/n", semval);
    }
}
 
void * consumer_f(void * arg)
{
    int semval = 0;
    while(running)
    {
        usleep(1);
        sem_wait(&sem);
        sem_getvalue(&sem, &semval);
        printf("消费,总数量:%d/n", semval);
    }
}

 

作者“张立斌”

(免责声明:文章内容如涉及作品内容、版权和其它问题,请及时与我们联系,我们将在第一时间删除内容,文章内容仅供参考)
收藏
  • 人气文章
  • 最新文章
  • 下载排行榜
  • 热门排行榜