簡體   English   中英

如何不阻止加入標准線程

[英]How to none blocked join to std thread

我想保持我的代碼整潔,並對需要執行連接或分離的任何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.
}

答案是信號量 您可以使用二進制信號量來同步線程。

您可以使用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();
}

您可以使用std :: promisestd :: future 更多信息在這里這里

#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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM