Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can multiple threads join the same boost::thread?

pthreads has undefined behavior if multiple threads try to join the same thread:

If multiple threads simultaneously try to join with the same thread, the results are undefined.

Is the same true for boost::threads? The documentation does not appears to specify this.

If it is undefined, then what would be a clean way for multiple threads to wait on one thread completing?

like image 365
Claudiu Avatar asked Aug 09 '26 00:08

Claudiu


1 Answers

If it is undefined, then what would be a clean way for multiple threads to wait on one thread completing?

The clean way would be for that one thread to inform the others that it is complete. A packaged_task contains a future which can be waited on, which can help us here.

Here's one way of doing that. I have used std::thread and std::packaged_task, but you could use the boost equivalents just as well.

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

expected output:

waiting...
wait over!
starting thread 2
starting thread 1
Hello, World
like image 115
Richard Hodges Avatar answered Aug 11 '26 16:08

Richard Hodges