首页 > 解决方案 > 如何无阻塞加入到标准线程

问题描述

我想保持我的代码干净并做正确的事情,任何std::thread我需要做的加入或分离,但我怎样才能(在主线程)等待另一个线程而不阻塞主线程的执行?

void do_computation()
{
    //  Calculate 1000 digits of Pi.
}


int main()
{
    std::thread td1(&do_computation);

    while (running)
    {
        //  Check if thread td1 finish and if yes print a message

        //  Here are some stuff of the main to do...
        //  Print to UI, update timer etc..

    }

    //  If the thread has not finished yet here, just kill it.
}

标签: c++stdthread

解决方案


答案是信号量。您可以使用二进制信号量来同步您的线程。

您可以使用 System V信号量或pthread互斥锁,但它们在某种程度上是 C++ 中的遗留物。不过,使用Tsuneo Yoshioka 的回答,我们可以实现 C++ 的信号量方式。

#include <mutex>
#include <condition_variable>

class Semaphore {
public:
    Semaphore (int count_ = 0)
        : count(count_) {}

    inline void notify()
    {
        std::unique_lock<std::mutex> lock(mtx);
        count++;
        cv.notify_one();
    }

    inline void wait()
    {
        std::unique_lock<std::mutex> lock(mtx);

        while(count == 0){
            cv.wait(lock);
        }
        count--;
    }

private:
    std::mutex mtx;
    std::condition_variable cv;
    int count;
};

您的实现可能会使用Semaphore该类,就像这样。

void do_computation()
{
    //calculate 1000 digits of Pi.

    semaphore.notify();
}


int main()
{
    Semaphore semaphore(0);
    std::thread td1(&do_computation);

    semaphore.wait();
}

推荐阅读