多个生产者,单个消费者,信号量
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | #include <stdio.h> #include <fcntl.h> #include <stdlib.h> #include <pthread.h> #include <semaphore.h> #define min(a,b) ((a)<(b)?(a):(b)) #define NBUFF 10 #define MAXNTHREADS 100 int nitems, nproducers; struct { int buff[NBUFF]; int nput, nputval; sem_t mutex, nempty, nstored; }shared; void *produce( void *), *consume( void *); int main( int argc, char **argv) { int i, count[MAXNTHREADS]; pthread_t tid_produce[MAXNTHREADS], tid_consume; if (argc!=3) { fprintf (stderr, "./a.out <#items> <#producers>\n" ); exit (-1); } nitems= atoi (argv[1]); nproducers=min( atoi (argv[2]), MAXNTHREADS); sem_init(&shared.mutex, 0, 1); sem_init(&shared.nempty, 0, NBUFF); sem_init(&shared.nstored, 0, 0); pthread_setconcurrency(nproducers+1); for (i=0;i<nproducers;i++) { count[i]=0; pthread_create(&tid_produce[i], NULL, produce, &count[i]); } pthread_create(&tid_consume, NULL, consume, NULL); for (i=0;i<nproducers;i++) { pthread_join(tid_produce[i], NULL); printf ( "count[%d]=%d\n" , i, count[i]); } pthread_join(tid_consume, NULL); sem_destroy(&shared.mutex); sem_destroy(&shared.nempty); sem_destroy(&shared.nstored); exit (0); } void *produce( void *arg) { for (;;) { sem_wait(&shared.nempty); sem_wait(&shared.mutex); if (shared.nput>=nitems) { sem_post(&shared.nempty); sem_post(&shared.mutex); return NULL; } shared.buff[shared.nput%NBUFF]=shared.nputval; shared.nput++; shared.nputval++; sem_post(&shared.mutex); sem_post(&shared.nstored); *(( int *)arg) += 1; } return NULL; } void *consume( void *arg) { int i; for (i=0;i<nitems;i++) { sem_wait(&shared.nstored); sem_wait(&shared.mutex); if (shared.buff[i%NBUFF]!=i) { printf ( "buff[%d]=%d\n" , i%NBUFF, shared.buff[i%NBUFF]); } sem_post(&shared.mutex); sem_post(&shared.nempty); } return NULL; } |
运行结果如下:
1 2 3 4 5 6 7 | $ ./a.out 1000000 6 count[0]=619 count[1]=23982 count[2]=263473 count[3]=208842 count[4]=241089 count[5]=261995 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!