天天看點

Linux網絡程式設計:生産者消費者問題

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)

        usleep(1);

        sem_wait(&sem);

        printf("消費,總數量:%d\n", semval);

繼續閱讀