如何不阻止加入标准线程

时间:2019-01-01 10:03:31

标签: c++ stdthread

我想保持我的代码整洁,并对需要进行连接或分离的任何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.
}

2 个答案:

答案 0 :(得分:1)

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

您可以使用 System V 信号量或 pthread 互斥量,但是它们在C ++中还是旧的。不过,使用Tsuneo Yoshioka's answer,我们可以实现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();
}

答案 1 :(得分:-2)

您可以使用std::promisestd::future。更多信息herehere

#include <vector>
#include <thread>
#include <future>
#include <numeric>
#include <iostream>
#include <chrono>

void accumulate(std::vector<int>::iterator first,
                std::vector<int>::iterator last,
                std::promise<int> accumulate_promise)
{
    int sum = std::accumulate(first, last, 0);
    accumulate_promise.set_value(sum);  // Notify future
}

void do_work(std::promise<void> barrier)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    barrier.set_value();
}

int main()
{
    // Demonstrate using promise<int> to transmit a result between threads.
    std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
    std::promise<int> accumulate_promise;
    std::future<int> accumulate_future = accumulate_promise.get_future();
    std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
                            std::move(accumulate_promise));
    accumulate_future.wait();  // wait for result
    std::cout << "result=" << accumulate_future.get() << '\n';
    work_thread.join();  // wait for thread completion

    // Demonstrate using promise<void> to signal state between threads.
    std::promise<void> barrier;
    std::future<void> barrier_future = barrier.get_future();
    std::thread new_work_thread(do_work, std::move(barrier));
    barrier_future.wait();
    new_work_thread.join();
}