C中带pthreads的printf
我正在使用pthreads处理生产者/消费者问题。我目前正在尝试让制作人工作,并使用printf语句查看我的问题所在。问题是代码编译得很好,但当我运行它时,它什么都不做,但似乎运行得很好。我尝试将第一行设置为printf语句,但即使这样也无法打印。我也尝试过使用fflush,但我的想法已经没有了。我的问题是,为什么连第一个printf语句都会被跳过C中带pthreads的printf,c,pthreads,C,Pthreads,我正在使用pthreads处理生产者/消费者问题。我目前正在尝试让制作人工作,并使用printf语句查看我的问题所在。问题是代码编译得很好,但当我运行它时,它什么都不做,但似乎运行得很好。我尝试将第一行设置为printf语句,但即使这样也无法打印。我也尝试过使用fflush,但我的想法已经没有了。我的问题是,为什么连第一个printf语句都会被跳过 #include <pthread.h> #include <stdlib.h> #include <stdio.h&
#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);
}
#包括
#包括
#包括
无效*生产者();
pthread_mutex_t lock;
pthread_cond_t done、full、empty;
int缓冲区[10];
int in=0,out=0;
整数最小值=0,最大值=0,numOfItems=0,总计=0;
双平均值;
void*producer(){
srand(时间(空));
int n=rand();
int i;
对于(i=0;i
pthread\u mutex\u init
初始化互斥体指向的互斥体对象
根据mutexattr中指定的互斥体属性。如果互斥
为NULL
,则使用默认属性
LinuxThreads实现只支持一个互斥体属性,即
互斥类型。。。互斥体的种类决定了它是否可以通过
已经拥有它的线程。默认类型为快速
如果互斥锁已被调用线程锁定,则
pthread\u mutex\u lock
取决于互斥的类型。如果互斥量为
fast类,调用线程将挂起,直到禁用互斥锁
解锁,从而有效地导致调用线程死锁
这就是你的制作人的遭遇:它会在通话中死锁
pthread_mutex_lock(&lock);
-除了不太可能的情况n<2-因此不产生输出。你说程序运行,这是什么意思?它是否像在无限循环中一样运行?它是否立即无误退出?如果“它什么也不做,但似乎运行良好”是您的测试,我可以很容易地编写许多优秀的程序。:)换句话说:您不是很清楚,很难理解您的意思。控制台输出可能是行缓冲的。在字符串末尾添加一个
\n
,或者如果要使用printf进行调试,请使用fflush(stdout)
,如果in!=10
您没有解锁mutex在哪里检查线程创建是否成功?那么你怎么知道它成功了呢。默认情况下,线程是可连接的。
pthread_mutex_lock(&lock);