gpt4 book ai didi

c - 在 C 中使用 pthreads 的 printf

转载 作者:太空宇宙 更新时间:2023-11-04 04:46:27 24 4
gpt4 key购买 nike

我现在正在使用 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);
}

最佳答案

man pthread_mutex_init

pthread_mutex_init initializes the mutex object pointed to by mutex according to the mutex attributes specified in mutexattr. If mutexattr is NULL, default attributes are used instead.

The LinuxThreads implementation supports only one mutex attributes, the mutex kind... The kind of a mutex determines whether it can be locked again by a thread that already owns it. The default kind is fast...

If the mutex is already locked by the calling thread, the behavior of pthread_mutex_lock depends on the kind of the mutex. If the mutex is of the fast kind, the calling thread is suspended until the mutex is unlocked, thus effectively causing the calling thread to deadlock.

这就是您的制作人会发生的情况:它在通话中陷入僵局

    pthread_mutex_lock(&lock);

- 除了不太可能的情况 n < 2 - 因此不产生任何输出。

关于c - 在 C 中使用 pthreads 的 printf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20404047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com