多个生产者,单个消费者,信号量

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
posted @   东宫得臣  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示