Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::thread: How to wait (join) for any of the given threads to complete?

For example, I have two threads, t1 and t2. I want to wait for t1 or t2 to finish. Is this possible?

If I have a series of threads, say, a std::vector<std::thread>, how can I do it?

like image 751
t123yh Avatar asked Apr 25 '17 15:04

t123yh


People also ask

How do you wait for threads?

The wait() Method Simply put, calling wait() forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object. For this, the current thread must own the object's monitor.

What will happen if you don't use the Join In thread?

The join part means the main program will wait for the thread to end before continuing. Without join, the main program will end and the thread will continue.

How do you join a thread in C++?

To wait for a thread use the std::thread::join() function. This function makes the current thread wait until the thread identified by *this has finished executing. A C++ program is given below.

Do I have to join a thread?

no, you can detach one thread if you want it to leave it alone. If you start a thread, either you detach it or you join it before the program ends, otherwise this is undefined behaviour.


1 Answers

There's always wait & notify using std::condition_variable, e.g.:

std::mutex m;
std::condition_variable cond;
std::atomic<std::thread::id> val;

auto task = [&] {
    std::this_thread::sleep_for(1s); // Some work

    val = std::this_thread::get_id();
    cond.notify_all();
};

std::thread{task}.detach();
std::thread{task}.detach();
std::thread{task}.detach();

std::unique_lock<std::mutex> lock{m};
cond.wait(lock, [&] { return val != std::thread::id{}; });

std::cout << "Thread " << val << " finished first" << std::endl;

Note: val doesn't necessarily represent the thread that finished first as all threads finish at about the same time and an overwrite might occur, but it is only for the purposes of this example.

like image 115
Felix Glas Avatar answered Oct 06 '22 01:10

Felix Glas