任何帮助将不胜感激!
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#define MAX 10
int buffer[MAX];
int fill = 0;
int use = 0;
int count = 0;
int loops = 15;
void put(int value) {
buffer[fill] = value;
fill = (fill + 1) % MAX;
count++;
printf("putting %d\n", value);
}
int get() {
int tmp = buffer[use];
use = (use + 1) % MAX;
count--;
return tmp;
}
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c_empty = PTHREAD_COND_INITIALIZER;
pthread_cond_t c_fill = PTHREAD_COND_INITIALIZER;
void *producer(void *arg) {
printf("producer starts\n");
int i;
for (i = 0; i < loops; i++) {
pthread_mutex_lock(&mutex); // p1
while (count == MAX) // p2
pthread_cond_wait(&c_empty, &mutex); // p3
put(i); // p4
pthread_cond_signal(&c_fill); // p5
pthread_mutex_unlock(&mutex); // p6
}
return NULL;
}
void *consumer(void *arg) {
printf("consumer starts\n");
int i;
for (i = 0; i < loops; i++) {
pthread_mutex_lock(&mutex); // c1
while (count == 0) // c2
pthread_cond_wait(&c_fill, &mutex); // c3
int tmp = get(); // c4
pthread_cond_signal(&c_empty); // c5
pthread_mutex_unlock(&mutex); // c6
printf("consuming: %d\n", tmp);
}
return NULL;
}
int main(int argc, char *argv[]) {
printf("parent: begin\n");
pthread_t p, x;
pthread_create(&p, NULL, producer, NULL);
pthread_create(&x, NULL, consumer, NULL);
printf("parent: end\n");
return 0;
}
生成文件:
all: wcountb
wcountb: wcountb.c
gcc -g -Wall -o wcountb wcountb.c -lpthread
答案 0 :(得分:1)
在主要结束时,您应该呼叫pthread_join
,如下所示:
...
pthread_join(p, NULL);
pthread_join(x, NULL);
return 0;
}
如果没有该调用,则会创建线程,当您到达main()
的末尾时,您的程序将终止,因此您的线程可能能够完成其工作,或者不能,这解释了有时你的代码有效的事实。
pthread_join()函数应暂停执行调用线程,直到目标线程终止,除非目标线程已经终止。
取自pthread_join()
的{{3}}。
一个几乎相关的问题在于manual。