C++ 条件变量指示分离线程执行停止的结束

标签 c++ multithreading condition-variable

我正在处理一些代码,其中生成了一个分离的线程,做了一些工作,然后应该等待来自 main() 的信号,然后再将另一个信号发送回 main 指示该线程已退出。

我对条件变量相当陌生,但是我之前使用过一些多线程代码。 (主要是互斥体。)

这是我试图实现的,但它的行为并不符合我的预期。 (可能我误解了什么。)

这背后的想法是将包含两个标志的结构传递给每个分离的线程。第一个标志表示 main() 表示“可以退出,并结束线程函数”。第二个标志由线程本身设置,并向 main() 发出信号,表明线程确实已退出。 (这只是为了确认来自 main() 的信号已正确收到并发回一些内容。)

#include <cstdlib> // std::atoi
#include <iostream>
#include <thread>
#include <vector>
#include <random>
#include <future>
#include <condition_variable>
#include <mutex>

struct ThreadStruct
{

    int id;

    std::condition_variable cv;
    std::mutex m;

    int ok_to_exit;
    int exit_confirm;

};



void Pause()
{
    std::cout << "Press enter to continue" << std::endl;
    std::cin.get();
}


void detachedThread(ThreadStruct* threadData)
{
    std::cout << "START: Detached Thread " << threadData->id << std::endl;
    
    // Performs some arbitrary amount of work.
    for(int i = 0; i < 100000; ++ i);

    std::cout << "FINISH: Detached thread " << threadData->id << std::endl;
    
    std::unique_lock<std::mutex> lock(threadData->m);
    std::cout << "WAIT: Detached thread " << threadData->id << std::endl;
    threadData->cv.wait(lock, [threadData]{return threadData->ok_to_exit == 1;});
    std::cout << "EXIT: Detached thread " << threadData->id << std::endl;
    threadData->exit_confirm = 1;

}

int main(int argc, char** argv)
{
    
    int totalThreadCount = 1;

    ThreadStruct* perThreadData = new ThreadStruct[totalThreadCount];
    std::cout << "Main thread starting " << totalThreadCount << " thread(s)" << std::endl;

    for(int i = totalThreadCount - 1; i >= 0; --i)
    {
        perThreadData[i].id = i;
        perThreadData[i].ok_to_exit = 0;
        perThreadData[i].exit_confirm = 0;
                
        std::thread t(detachedThread, &perThreadData[i]);
        t.detach();
            
    }


    for(int i{0}; i < totalThreadCount; ++i)
    {
        ThreadStruct *threadData = &perThreadData[i];
        
        std::cout << "Waiting for lock - main() thread" << std::endl;
        std::unique_lock<std::mutex> lock(perThreadData[i].m);
        std::cout << "Lock obtained - main() thread" << std::endl;
        perThreadData[i].cv.wait(lock);

        threadData->ok_to_exit = 1;

        // added after comment from Sergey
        threadData->cv.notify_all(); 

        std::cout << "Done - main() thread" << std::endl;
        
    }

    for(int i{0}; i < totalThreadCount; ++i)
    {
        std::size_t thread_index = i;
        ThreadStruct& threadData = perThreadData[thread_index];
        
        std::unique_lock<std::mutex> lock(threadData.m);
        std::cout << "i=" << i << std::endl;
        int &exit_confirm = threadData.exit_confirm;
        threadData.cv.wait(lock, [exit_confirm]{return exit_confirm == 1;});
        std::cout << "i=" << i << " finished!" << std::endl;
    }

    Pause();

    return 0;
}

这会运行到以下行:

WAIT: Detached thread 0

但是分离的线程永远不会退出。我做错了什么?

编辑:进一步实验 - 这有帮助吗?

我认为通过删除一个步骤来简化事情可能会有所帮助。在下面的示例中,main() 不会向分离线程发出信号,它只是等待来自分离线程的信号。 p>

但同样,此代码在打印 DROP 后挂起...这意味着分离的线程正常退出,但 main() 不知道这一点。

#include <cstdlib> // std::atoi
#include <iostream>
#include <thread>
#include <vector>
#include <random>
#include <future>
#include <condition_variable>
#include <mutex>

struct ThreadStruct
{

    int id;

    std::condition_variable cv;
    std::mutex m;

    int ok_to_exit;
    int exit_confirm;

};



void Pause()
{
    std::cout << "Press enter to continue" << std::endl;
    std::cin.get();
}


void detachedThread(ThreadStruct* threadData)
{
    std::cout << "START: Detached Thread " << threadData->id << std::endl;
    
    // Performs some arbitrary amount of work.
    for(int i = 0; i < 100000; ++ i);

    std::cout << "FINISH: Detached thread " << threadData->id << std::endl;
    
    std::unique_lock<std::mutex> lock(threadData->m);
    
    std::cout << "EXIT: Detached thread " << threadData->id << std::endl;
    threadData->exit_confirm = 1;

    threadData->cv.notify_all();
    std::cout << "DROP" << std::endl;

}

int main(int argc, char** argv)
{
    
    int totalThreadCount = 1;

    ThreadStruct* perThreadData = new ThreadStruct[totalThreadCount];
    std::cout << "Main thread starting " << totalThreadCount << " thread(s)" << std::endl;

    for(int i = totalThreadCount - 1; i >= 0; --i)
    {
        perThreadData[i].id = i;
        perThreadData[i].ok_to_exit = 0;
        perThreadData[i].exit_confirm = 0;
                
        std::thread t(detachedThread, &perThreadData[i]);
        t.detach();
            
    }

    for(int i{0}; i < totalThreadCount; ++i)
    {
        std::size_t thread_index = i;
        ThreadStruct& threadData = perThreadData[thread_index];
        
        std::cout << "Waiting for mutex" << std::endl;
        std::unique_lock<std::mutex> lock(threadData.m);
        std::cout << "i=" << i << std::endl;
        int &exit_confirm = threadData.exit_confirm;
        threadData.cv.wait(lock, [exit_confirm]{return exit_confirm == 1;});
        std::cout << "i=" << i << " finished!" << std::endl;
    }

    Pause();

    return 0;
}

最佳答案

您的 lambda 正在按值捕获,因此它永远不会看到对 exit_confim 所做的更改.

改为通过引用捕获:

int& exit_confirm = threadData.exit_confirm;
threadData.cv.wait(lock, [&exit_confirm] { return exit_confirm == 1; });
//                        ^
//                        | capture by-reference

您还需要delete[]你什么new[]也如此

delete[] ThreadStruct;

当您完成 struct 时s。


我还注意到释放后有一些堆使用情况,但当我对代码进行一些简化时,这种情况神奇地消失了。我没有进一步调查。

一些建议:

  • 将代码移至 ThreadStruct处理 ThreadStruct 的类成员变量和锁。它通常会使阅读和维护变得更简单。
  • 删除未使用的变量和 header 。
  • 请勿使用new[]/delete[] 。对于此示例,您可以使用 std::vector<ThreadStruct>相反。
  • 不要detach()完全没有 - 我没有在下面做任何事情,但我建议使用 join() (在附加线程上)进行最终同步。这就是它的用途。
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

struct ThreadStruct {
    int id;

    // move this function into the ThreadStruct class
    void detachedThread() {
        std::cout << "START: Detached Thread " << id << std::endl;
        // Performs some arbitrary amount of work (optimized away here)
        std::cout << "FINISH: Detached thread " << id << std::endl;

        std::lock_guard<std::mutex> lock(m);

        std::cout << "EXIT: Detached thread " << id << std::endl;
        exit_confirm = 1;

        cv.notify_all();
        std::cout << "DROP" << std::endl;
    }

    // add support functions instead of doing these things in your normal code
    void wait_for_exit_confirm() {
        std::unique_lock<std::mutex> lock(m);
        cv.wait(lock, [this] { return exit_confirm == 1; });
    }

    void spawn_detached() {
        std::thread(&ThreadStruct::detachedThread, this).detach();
    }

private:
    std::condition_variable cv;
    std::mutex m;

    int exit_confirm = 0;           // initialize
};

综上所述,main变得更干净一点:

int main() {
    int totalThreadCount = 1;

    std::vector<ThreadStruct> perThreadData(totalThreadCount);

    std::cout << "Main thread starting " << perThreadData.size() << " thread(s)\n";

    int i = 0;
    for(auto& threadData : perThreadData) {
        threadData.id = i++;
        threadData.spawn_detached();
    }

    for(auto& threadData : perThreadData) {
        std::cout << "Waiting for mutex" << std::endl;
        std::cout << "i=" << threadData.id << std::endl;
        threadData.wait_for_exit_confirm();
        std::cout << "i=" << threadData.id << " finished!" << std::endl;
    }

    std::cout << "Press enter to continue" << std::endl;
    std::cin.get();
}

关于C++ 条件变量指示分离线程执行停止的结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66661083/

相关文章:

multithreading - Rust 2021 与 2018 : trait `std::marker::Send` is not implemented - what is the correct way to do this in 2021 edition?

c++ - Boost Asio - 如何知道处理程序队列何时为空?

c# - 如何将工作编码到单线程 C#

c++ - 为什么pthread_cond_signal会导致死锁

c - 条件变量有队列吗?

c++ - QLabel在调整大小时切断文本

c++ - 并发::任务析构函数导致调用在有效用例中中止

c++ - 没有智能指针经验的多态对象的转换类型

C++多维数组初始化

c++ - 测试等待队列中 condition_variables 的多个线程