생산자 소비자 - c 언어 실현

2437 단어 데이터 구조
#include 
#include 
#include 
#include 
#include 
#include  

pthread_mutex_t mtx;
pthread_cond_t cond_add;
pthread_cond_t cond_del;
int pool;
int size;

#define THREADS 3
pthread_t tid_pd[THREADS];
pthread_t tid_cs[THREADS];

void producer(void *id)
{
	int threadid = *((int *)id);
	printf("producer threadid %d started.
", threadid); while(1) { retry: pthread_mutex_lock(&mtx); if(pool >= size) { pthread_cond_wait(&cond_del, &mtx); pthread_mutex_unlock(&mtx); goto retry; } pool ++; printf("p%d add a good, pool is %d.
", threadid, pool); pthread_cond_signal(&cond_add); pthread_mutex_unlock(&mtx); srand((unsigned)time(NULL)); } return; } void consumer(void *id) { int threadid = *((int *)id); printf("consumer threadid %d started.
", threadid); while(1) { retry: pthread_mutex_lock(&mtx); if(pool <= 0) { pthread_cond_wait(&cond_add, &mtx); pthread_mutex_unlock(&mtx); goto retry; } pool --; printf("c%d del a good, pool is %d.
", threadid, pool); pthread_cond_signal(&cond_del); pthread_mutex_unlock(&mtx); } return; } int main(int argc, char const *argv[]) { /* code */ pthread_mutex_init(&mtx, NULL); pthread_cond_init(&cond_add, NULL); pthread_cond_init(&cond_del, NULL); pool = 0; size = 10; int i; for(i = 0; i < THREADS; i ++) { if(pthread_create(&tid_pd[i], NULL, (void *)producer, (void *)(&i)) != 0) { printf("create producer thread %d error!
", i); return 0; } usleep(100000); } for(i = 0; i < THREADS; i ++) { if(pthread_create(&tid_cs[i], NULL, (void *)consumer, (void *)(&i)) != 0) { printf("create consumer thread %d error!
", i); return 0; } usleep(100000); } for(i = 0; i < THREADS; i ++) { if(pthread_join(tid_pd[i], NULL) != 0) { printf("join producer thread %d error!
", i); return 0; } } for(i = 0; i < THREADS; i ++) { if(pthread_join(tid_cs[i], NULL) != 0) { printf("join consumer thread %d error!
", i); return 0; } } pthread_mutex_destroy(&mtx); pthread_cond_destroy(&cond_add); pthread_cond_destroy(&cond_del); return 0; }

좋은 웹페이지 즐겨찾기