linux C semaphore producer-consumer model

 

 Critical section to a shared queue

Use amount of thread synchronization signal, here it is no longer necessary for locking operation.

 

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<semaphore.h>
#include<time.h>
#define NUM 5

int 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;

}

 

Guess you like

Origin blog.csdn.net/wwxy1995/article/details/94583036