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);
    }
}