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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With