【发布时间】:2013-12-05 15:33:15
【问题描述】:
我现在正在使用 pthreads 解决生产者/消费者问题。我目前只是想让生产者工作并使用 printf 语句来查看我的问题在哪里。问题是代码编译得很好,但是当我运行它时,它什么也没做,但似乎运行得很好。我尝试将第一行设置为 printf 语句,但即使这样也不会打印。我也尝试过使用 fflush ,但我的想法已经不多了。我的问题是为什么连第一个 printf 语句都会被跳过?
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
void *producer();
pthread_mutex_t lock;
pthread_cond_t done, full, empty;
int buffer[10];
int in = 0, out = 0;
int min = 0, max = 0, numOfItems = 0, total = 0;
double avg;
void *producer() {
srand(time(NULL));
int n = rand();
int i;
for(i = 0; i < n; i++)
{
int random = rand();
pthread_mutex_lock(&lock);
buffer[in++] = random;
if(in == 10)
{
pthread_cond_signal(&full);
printf("Buffer full");
pthread_mutex_unlock(&lock);
sleep(1);
}
}
pthread_exit(NULL);
}
void *consumer() {
pthread_exit(NULL);
}
int main(int argc, char *argv[]){
printf("test");
//Create threads and attribute
pthread_t ptid, ctid;
pthread_attr_t attr;
//Initialize conditions and mutex
pthread_cond_init(&full, NULL);
pthread_cond_init(&empty, NULL);
pthread_cond_init(&done, NULL);
pthread_mutex_init(&lock, NULL);
//Create joinable state
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
pthread_create(&ptid, &attr,(void *)producer,NULL);
pthread_create(&ctid, &attr,(void *)consumer,NULL);
pthread_join(ptid,NULL);
pthread_join(ctid,NULL);
printf("Program Finished!");
pthread_exit(NULL);
}
【问题讨论】:
-
你说程序运行,是什么意思?它是否像无限循环一样运行?它会立即退出而没有错误吗?
-
如果“它什么也没做,但似乎运行得很好”是你的测试,我可以很容易地编写出许多优秀的程序。 :) 换句话说:你不是很清楚,很难理解你的意思。
-
控制台输出可能是行缓冲的。在字符串末尾添加
\n,如果要使用printf进行调试,请使用fflush(stdout) -
如果
in != 10你没有解锁互斥锁 -
在哪里检查线程创建是否成功?那你怎么知道它成功了。线程默认是可连接的。