簡體   English   中英

多個線程可以加入相同的boost :: thread嗎?

[英]Can multiple threads join the same boost::thread?

如果多個線程嘗試加入同一個線程,則pthreads具有未定義的行為:

如果多個線程同時嘗試使用同一個線程進行連接,則結果是未定義的。

對於boost::thread s來說是一樣的嗎? 該文檔似乎沒有指定這一點。

如果它是未定義的,那么多個線程在一個線程完成時等待的干凈方式是什么?

如果它是未定義的,那么多個線程在一個線程完成時等待的干凈方式是什么?

干凈的方式是為那一個線程通知其他人它已完成。 一個packaged_task包含一個可以等待的future ,這可以幫助我們。

這是一種方法。 我使用過std :: thread和std :: packaged_task,但你也可以使用boost等價物。

#include <thread>
#include <mutex>
#include <future>
#include <vector>
#include <iostream>

void emit(const char* msg) {
    static std::mutex m;
    std::lock_guard<std::mutex> l(m);
    std::cout << msg << std::endl;
    std::cout.flush();
}

int main()
{
    using namespace std;

    auto one_task = std::packaged_task<void()>([]{
        emit("waiting...");
        std::this_thread::sleep_for(std::chrono::microseconds(500));
        emit("wait over!");
    });

    // note: convert future to a shared_future so we can pass it
    // to two subordinate threads simultaneously
    auto one_done = std::shared_future<void>(one_task.get_future());
    auto one = std::thread(std::move(one_task));

    std::vector<std::thread> many;
    many.emplace_back([one_done] {
        one_done.wait();
        // do my thing here
        emit("starting thread 1");
    });

    many.emplace_back([one_done] {
        one_done.wait();
        // do my thing here
        emit("starting thread 2");
    });

    one.join();
    for (auto& t : many) {
        t.join();
    }

    cout << "Hello, World" << endl;
    return 0;
}

預期產量:

waiting...
wait over!
starting thread 2
starting thread 1
Hello, World

我最終使用了boost::condition_variable ...粗略:

class thread_wrapper {
    boost::mutex mutex;
    boost::condition_variable thread_done_condition;
    bool thread_done = false;

    void the_func() {
        // ...
        // end of the thread
        {  
            boost:unique_lock<boost::mutex> lock(mutex);
            thread_done = true;
        }
        thread_done_condition.notify_all();
    }

    void wait_until_done() {
        boost::unique_lock<boost::mutex> lock(mutex);
        thread_done_condition.wait(lock, [this]{ return thread_done; });
    }
}

然后多個呼叫者可以安全地調用wait_until_done()

現在讓我感到震驚的是,以下內容也會起作用:

class thread_wrapper {
public:
    thread_wrapper() : thread([this]() { this->the_func(); }) { }

    void wait_until_done() {
        boost::unique_lock<boost::mutex> lock(join_mutex);
        thread.join();
    }

private:
    void the_func() {
        // ...
    }

    boost::mutex join_mutex;
    boost::thread thread;
}

暫無
暫無

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

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