线程——消费者生产者

xiaoxiao2021-02-28  120

#include <stdio.h> #include <pthread.h> #include <time.h> #include <string.h> int resources; pthread_mutex_t mutex; void delay() { unsigned int x,y; x = rand()000+1; while (x > 0) { y = rand()000+1; while (y > 0) { y--; } x--; } } void *producer(void *arg) { while (1) { pthread_mutex_lock(&mutex); delay(); resources += 2; printf("Produce 2 resources\n"); pthread_mutex_unlock(&mutex); } } void *consumer(void *arg) { while (1) { pthread_mutex_lock(&mutex); if (resources <= 0) { pthread_mutex_unlock(&mutex); continue; } delay(); resources--; printf("Consumer 1 resources, %d left\n", resources); pthread_mutex_unlock(&mutex); } } int main() { pthread_t p1, c1, c2, c3; int err; srand((unsigned int)time(NULL)); pthread_mutex_init(&mutex, NULL); err = pthread_create(&p1, NULL, producer, NULL); if (-1 == err) { printf("create p1 thread fail: %s\n", strerror(err)); return -1; } err = pthread_create(&c1, NULL, consumer, NULL); if (-1 == err) { printf("create c1 thread fail: %s\n", strerror(err)); return -1; } err = pthread_create(&c2, NULL, consumer, NULL); if (-1 == err) { printf("create c2 thread fail: %s\n", strerror(err)); return -1; } err = pthread_create(&c3, NULL, consumer, NULL); if (-1 == err) { printf("create c3 thread fail: %s\n", strerror(err)); return -1; } err = pthread_join(p1, NULL); if (0 != err) { printf("wait p1 thread fail: %s\n", strerror(err)); return -1; } err = pthread_join(c1, NULL); if (0 != err) { printf("wait c1 thread fail: %s\n", strerror(err)); return -1; } err = pthread_join(c2, NULL); if (0 != err) { printf("wait c2 thread fail: %s\n", strerror(err)); return -1; } err = pthread_join(c3, NULL); if (0 != err) { printf("wait c3 thread fail: %s\n", strerror(err)); return -1; } pthread_mutex_destroy(&mutex); return 0; }
转载请注明原文地址: https://www.6miu.com/read-66297.html

最新回复(0)