⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 prodcom.c

📁 linux下多线程实现生产者消费者及用并行算法求圆周率等经典算法
💻 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 + -