多个生产者,单个消费者,互斥锁

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
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
 
#define min(a,b) ((a)<(b)?(a):(b))
#define MAXNITEMS   1000000
#define MAXNTHREADS 10
 
int nitems;
struct {
    pthread_mutex_t mutex;
    int buff[MAXNITEMS];
    int nput;
    int nval;
}shared={
    PTHREAD_MUTEX_INITIALIZER
};
 
void *produce(void *), *consume(void *);
 
int main(int argc, char **argv) {
    int i, nthreads, count[MAXNTHREADS];
    pthread_t tid_produce[MAXNTHREADS], tid_consume;
 
    if(argc!=3) {
        fprintf(stderr, "usage: ./a.out <#items> <#threads>.\n");
        exit(-1);
    }
    nitems=min(atoi(argv[1]), MAXNITEMS);
    nthreads=min(atoi(argv[2]), MAXNTHREADS);
 
    pthread_setconcurrency(nthreads);
 
    for(i=0;i<nthreads;i++) {
        count[i]=0;
        pthread_create(&tid_produce[i], NULL, produce, &count[i]);
    }
 
    for(i=0;i<nthreads;i++) {
        pthread_join(tid_produce[i], NULL);
        printf("count[%d]=%d\n", i, count[i]);
    }
 
    pthread_create(&tid_consume, NULL, consume, NULL);
    pthread_join(tid_consume, NULL);
 
    exit(0);
}
 
void *produce(void *arg) {
    for(;;) {
        pthread_mutex_lock(&shared.mutex);
        if(shared.nput>=nitems) {
            pthread_mutex_unlock(&shared.mutex);
            return NULL;
        }
        shared.buff[shared.nput]=shared.nval;
        shared.nput++;
        shared.nval++;
        pthread_mutex_unlock(&shared.mutex);
        *((int *)arg)+=1;
    }
}
 
void *consume(void *arg) {
    int i;
    for(i=0;i<nitems;i++) {
        if(shared.buff[i]!=i) {
            printf("buff[%d]=%d\n", i, shared.buff[i]);
        }
    }
    return NULL;
}

结果如下:

1
2
3
4
5
6
7
$ gcc prodcons.c -pthread
$ ./a.out 10000000 5
count[0]=253230
count[1]=285783
count[2]=129999
count[3]=157355
count[4]=173633
posted @   东宫得臣  阅读(14)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示