临界区为一个共享队列
使用信号量进行线程同步,这里不再需要进行加锁操作。
#include
#include
#include
#include
#include
#define NUM 5int queue[NUM];
sem_t black_number, product_number;void *producer(void* arg)
{int i = 0;while(1){sem_wait(&black_number); // 空格数--, 为0阻塞queue[i] = rand() %1000 + 1;printf("-------Produce-----%d\n", queue[i]);sem_post(&product_number); // 产品数++i = (i+1) % NUM;sleep(rand()%3);}return NULL;
}void *consumer(void* arg)
{int i = 0;while(1){sem_wait(&product_number); // 产品数--,为0的话阻塞printf("-Consume---%d\n",queue[i]);queue[i] = 0; sem_post(&black_number); // 空格数++i = (i+1)%NUM;sleep(rand()%3);}return NULL;}int main()
{pthread_t pid,cid;
// srand(time(NULL));sem_init(&black_number, 0 , NUM);sem_init(&product_number, 0, 0);pthread_create(&pid, NULL, producer, NULL);pthread_create(&cid, NULL, consumer, NULL);pthread_join(pid,NULL);pthread_join(cid,NULL);sem_destroy(&black_number);sem_destroy(&product_number);return 0;}