gpt4 book ai didi

c - C-pthread条件变量

转载 作者:行者123 更新时间:2023-12-03 12:59:22 27 4
gpt4 key购买 nike

所以我有一个while循环,它可以处理多个线程,并且我希望只要所有线程都在工作,它就可以工作,例如:

while(*threads are working*) {
pthread_mutex_lock
if(stack is not empty) {
pthread_cond_broadcast
*critical work*
pthread_mutex_unlock
}
else {
pthread_cond_wait
pthread_mutex_unlock
}

我基本上希望运行这个while循环,直到所有线程都检查了堆栈是否为空并在其他情况下正在等待。非常欢迎所有提示,谢谢。

最佳答案

请记住,条件变量只是表示封闭程序中的某些条件已发生变化。使用条件变量时,最重要的事情是了解该条件是什么并确保对其进行正确建模。条件通常也称为谓词。

在您的情况下,您的线程既充当共享堆栈上工作的生产者又充当消费者。如果线程用尽了工作,它将进入等待状态,只有在满足以下条件之一时才应从该状态返回:

  • 其他一些线程将工作压入堆栈。在这种情况下,您希望您的线程醒来以帮助新近完成的工作。
  • 所有线程都已进入等待状态。在那种情况下,没有更多的工作了,并且由于所有线程都已完成,因此不会再有任何工作被压入堆栈。

  • 这两个条件的析取构成您的谓词。

    第一个条件已经在程序中建模,因为您可以简单地检查堆栈以找出是否有任何新工作可用。但是,第二个条件不是。您无法检查当前处于等待状态的线程数。

    解决方案是对该条件也进行建模,这可以通过引入一个计数器轻松完成:
    int threads_waiting = 0;
    while(true) {
    pthread_mutex_lock
    if(stack is not empty) {
    *critical work*
    if(i_pushed_some_work_on_the_stack) {
    pthread_cond_broadcast // wake up any threads that have gone to sleep
    // because the stack ran out of work
    }
    pthread_mutex_unlock
    } else {
    ++threads_sleeping
    if(threads_sleeping == number_of_threads) {
    pthread_cond_broadcast // wake up any threads waiting for
    // the last thread to finish
    pthread_mutex_unlock // ... and we're done!
    return
    }
    while(true) {
    pthread_cond_wait
    if(stack is not empty) {
    // there is more work available; continue outer loop
    --threads_sleeping
    break;
    } else if(threads_sleeping == number_of_threads) {
    // everybody is done, so let's return
    pthread_mutex_unlock
    return
    } else {
    // spurious wakeup; go back to sleep
    }
    }
    pthread_mutex_unlock
    }

    请注意,只要谓词发生变化,我们如何调用 pthread_cond_broadcast,从 pthread_cond_wait返回后,我们将检查封闭条件以弄清楚下一步该怎么做。

    关于c - C-pthread条件变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46707531/

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