gpt4 book ai didi

c - pthread_cond_broadcast 不向线程发送信号

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

我真的很难理解如何以允许线程同时运行的方式锁定和解锁互斥体。现在我试图让每个线程都做一些事情,然后等到所有线程都准备好,然后重复它。这应该反复发生,所以我把它都放在一个条件循环中。我的问题是,似乎我的广播从未被任何线程接收到,因为等待信号的每个线程都在永远等待,而发送信号的线程仍在继续。

我简化了我的代码,使其尽可能简单,同时仍可编译和运行:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

#define num_threads 4

int repeat = 1;
int timesLooped = 0;
int waitingThreads = 0;
int threadNo = -1;
pthread_mutex_t mutex1;
pthread_cond_t condition;


//thread body
void* threadBody(void* arg){


//sensitive info: requires lock
if(pthread_mutex_lock(&mutex1)){ printf("error1\n"); }
threadNo++;
int threadId = threadNo;
//other info is set here as well in my code
if(pthread_mutex_unlock(&mutex1)){ printf("error2\n"); }

//main loop in the thread body
while(repeat == 1){

if(pthread_mutex_lock(&mutex1)){ printf("error3\n"); }

//wait until all threads are ready
while(waitingThreads < num_threads - 1){

printf(" %d! ", threadId);
waitingThreads++;
pthread_cond_wait(&condition, &mutex1);

printf(" %d ", threadId);
if(pthread_mutex_unlock(&mutex1)){ printf("error4\n"); }

}

//last thread will broadcast
if(waitingThreads == num_threads - 1){

printf("\n\nthread %d was last! broadcasting to let everyone proceed...", threadId);
timesLooped++;
waitingThreads = 0;
if(timesLooped == 3){
repeat = 0;
}
sleep(1);
pthread_cond_broadcast(&condition);
if(pthread_mutex_unlock(&mutex1)){ printf("error5\n"); }





}



}
printf("\n\nexiting thread %d\n", threadId);
pthread_exit((void*) arg);
}





int main(int argc, char** argv){

pthread_t threads[num_threads];
void* retval;

//create threads
for(long i = 0; i < num_threads; i++){
pthread_create(&threads[i], NULL, threadBody, (void*) i);
}

//join threads
for(long j = 0; j < num_threads; j++){
pthread_join(threads[j], &retval);
}


printf("\n\nDONE\n");
}

这给了我一个输出:

thread 3 was last! broadcasting to let everyone proceed...

thread 2 was last! broadcasting to let everyone proceed...

thread 1 was last! broadcasting to let everyone proceed...

exiting thread 1 (deadlock, other threads never exit)

最佳答案

你的程序中至少有两个错误。

  1. 您有一场数据竞赛(参见 blog post)。

    当线程 0num_threads - 1 访问 waitingThreadsif (waitingThreads == num_threads - 1) ...,他们在锁外这样做(即他们比赛)。

  2. 您不允许除最后一个以外的线程运行(这是您的主要问题)。

    pthread_cond_wait两个条件都已发出信号时返回,并且可以重新获取互斥体。

    但是您的最后一个线程在释放它时立即重新获取互斥量,因此其他线程无法继续。

    我希望如果您在最后一个线程中的 pthread_mutex_unlock 之后添加 sleepusleep,您的程序将按照您的预期开始工作.

关于c - pthread_cond_broadcast 不向线程发送信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50689737/

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