首页 > 解决方案 > 工作线程在执行太快后永久休眠

问题描述

我正在尝试将线程合并到我的项目中,但有一个问题,即仅使用 1 个工作线程使其永久“入睡”。也许我有一个比赛条件,但就是没有注意到它。

我的PeriodicThreads对象维护着一组线程。一旦PeriodicThreads::exec_threads()被调用,线程就会被通知,被唤醒并执行它们的任务。之后,他们又睡着了。

这种工作线程的功能:

void PeriodicThreads::threadWork(size_t threadId){
    //not really used, but need to decalre to use conditional_variable:
    std::mutex mutex;
    std::unique_lock<std::mutex> lck(mutex);

    while (true){
        // wait until told to start working on a task:
        while (_thread_shouldWork[threadId] == false){
            _threads_startSignal.wait(lck);
        }

        thread_iteration(threadId);    //virtual function

        _thread_shouldWork[threadId] = false;   //vector of flags
        _thread_doneSignal.notify_all();

    }//end while(true) - run until terminated externally or this whole obj is deleted 
}

正如你所看到的,每个线程都在监控自己的标志向量中的条目,一旦它看到它的标志为真 - 执行任务然后重置它的标志。

这是可以唤醒所有线程的函数:

std::atomic_bool _threadsWorking =false;

//blocks the current thread until all worker threads have completed:
void PeriodicThreads::exec_threads(){
    if(_threadsWorking ){ 
        throw std::runtime_error("you requested exec_threads(), but threads haven't yet finished executing the previous task!");
    }

    _threadsWorking = true;//NOTICE: doing this after the exception check.

    //tell all threads to unpause by setting their flags to 'true'
    std::fill(_thread_shouldWork.begin(),  _thread_shouldWork.end(),  true);
    _threads_startSignal.notify_all();

    //wait for threads to complete:

    std::mutex mutex;
    std::unique_lock<std::mutex> lck(mutex); //lock & mutex are not really used.

    auto isContinueWaiting = [&]()->bool{
        bool threadsWorking = false; 
        for (size_t i=0;  i<_thread_shouldWork.size();  ++i){
            threadsWorking |= _thread_shouldWork[i];
        }
        return threadsWorking;
    };

    while (isContinueWaiting()){
        _thread_doneSignal.wait(lck);
    }

    _threadsWorking = false;//set atomic to false 
}

调用exec_threads()数百次或在极少数情况下数千次连续迭代都可以正常工作。调用发生在主线程的while循环中。它的工作线程处理任务,重置其标志并返回睡眠直到下一个exec_threads(),依此类推。

然而,在那之后的一段时间,程序突然进入“休眠”状态,似乎暂停了,但没有崩溃。

在这样的“休眠”期间,在while-loop我的任何 condition_variables 处设置断点实际上不会导致触发该断点。


偷偷摸摸地,我创建了自己的验证线程(与 并行main)并监视我的PeriodicThreads对象。当它进入休眠状态时,我的验证线程不断向控制台输出当前没有线程正在运行(_threadsWorking原子的PeriodicThreads永久设置为 false)。但是,在其他测试期间true,一旦“休眠问题”开始,原子仍然保持不变。

奇怪的是,如果我PeriodicThreads::run_thread在重置其标志之前强制休眠至少 10 微秒,一切都会正常工作,并且不会发生“休眠”。否则,如果我们允许线程非常快地完成它的任务,它可能会导致整个问题。

我已经将每个都包裹condition_variable在一个 while 循环中,以防止虚假唤醒触发转换,并在notify_all其上调用之前.wait()调用的情况。 关联

请注意,即使我只有 1 个工作线程也会发生这种情况

可能是什么原因?

编辑

atomic_bool放弃这些向量标志并仅在具有 1 个工作线程的单个上进行测试仍然显示相同的问题。

标签: c++multithreadingcondition-variable

解决方案


所有共享数据都应受互斥体保护。互斥体应该(至少)与共享数据具有相同的范围。

您的_thread_shouldWork容器是共享数据。您可以创建一个全局互斥体数组,每个互斥体都可以保护自己的_thread_shouldWork元素。(见下面的注释)。您还应该至少拥有与互斥锁一样多的条件变量。(您可以将 1 个互斥锁与多个不同的条件变量一起使用,但不应将多个不同的互斥锁与 1 个条件变量一起使用。)

Acondition_variable应该保护实际条件(在这种情况下,任何给定点的单个元素的状态_thread_shouldWork),互斥锁用于保护包含该条件的变量。

如果您只是使用随机的本地互斥锁(就像您在线程代码中一样)或者根本不使用互斥锁(在主代码中),那么所有的赌注都没有了。这是未定义的行为。虽然我可以看到它大部分时间都在工作(幸运)。我怀疑正在发生的是工作线程缺少来自主线程的信号。也可能是您的主线程缺少来自工作线程的信号。(线程A读取状态并进入while循环,然后线程B改变状态并发送通知,然后线程A进入睡眠状态……等待已经发送的通知)

具有本地范围的互斥锁是一个危险信号!

注意:如果您使用的是矢量,则必须小心,因为添加或删除项目可能会触发调整大小,这将在不先抓住互斥锁的情况下接触元素(因为当然矢量不知道您的互斥锁)。

使用数组时还必须注意虚假共享

编辑:这是@Kari 发现对解释虚假分享有用的视频 https://www.youtube.com/watch?v=dznxqe1Uk3E


推荐阅读