Linux 线程 生产者消费者问题 《Unix网络编程》

men_wen 2016-12-20 08:30:02
这个代码是《Unix网络编程卷2》第129页的代码:
#include <pthread.h>                                                          
#include <stdlib.h>
#include <stdio.h>

#define MAXNITEMS 1000000
#define MAXNTHREADS 5

int nitems;
struct {
pthread_mutex_t mutex;
int buff[MAXNTHREADS];
int nput;
int nval;
} shared = {
PTHREAD_MUTEX_INITIALIZER
};

void *producer(void *arg)
{
while(1) {
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 *consumer(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;
}

int main(void)
{
int i, nthreads, count[MAXNTHREADS];
pthread_t tid_producer[MAXNTHREADS], tid_consumer;

nitems = MAXNITEMS;
nthreads = MAXNTHREADS;

//pthread_setconcurrency(nthreads + 1);
for(i = 0; i < nthreads; i++) {
count[i] = 0;
pthread_create(&tid_producer[i], NULL, producer, &count[i]);
}

for(i = 0; i < nthreads; i++) {
pthread_join(tid_producer[i], NULL);
printf("count[%d] = %d\n", i, count[i]);
}

pthread_create(&tid_consumer, NULL, consumer, NULL);
pthread_join(tid_consumer, NULL);

exit(0);
}


运行两次的结果:
# SYNCHRONIZATION ./a.out
count[0] = 0
count[1] = 0
count[2] = 0
count[3] = 0
count[4] = 9
buff[5] = 9
buff[6] = 9
# SYNCHRONIZATION ./a.out
count[0] = 9
count[1] = 0
count[2] = 0
count[3] = 0
count[4] = 0
buff[5] = 9
buff[6] = 9


创建的生产者线程应该在 if(shared.nput >= nitems) 成立返回,nitems值为1000000,但是运行结果却是shared.nput等于9的时候退出,这是为什么?
...全文
107 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

23,128

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧