📄 prodcom.c
字号:
#include <pthread.h>#include <stdio.h>#include <semaphore.h>sem_t empty, full; // the global semaphoresint data; // shared bufferint num;// deposit 1, ..., num into the data buffervoid *Producer(void *arg) { int produced; printf("Producer created\n"); for (produced = 1; produced <= num; produced++) { sem_wait(&empty); data = produced; sem_post(&full); }}// fetch num items from the buffer and sum themvoid *Consumer(void *arg) { int total = 0, consumed; printf("Consumer created\n"); for (consumed = 0; consumed < num; consumed++) { sem_wait(&full); total = total+data; sem_post(&empty); } printf("for %d iterations, the total is %d\n", num, total);}int main(int argc, char *argv[]) { pthread_t pid, cid; num = atoi(argv[1]); sem_init(&empty, 0, 1); // sem empty = 1 sem_init(&full, 0, 0); // sem full = 0 printf("main started\n"); pthread_create(&pid, NULL, Producer, NULL); pthread_create(&cid, NULL, Consumer, NULL); pthread_join(pid, NULL); pthread_join(cid, NULL); printf("main done\n");}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -