To join a std::jthread
and wait for it to finish, you can use the join()
member function. Here’s an example that demonstrates how to join a std::jthread
:
#include <iostream>
#include <chrono>
#include <thread>
void workerThread()
{
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "Worker thread completed\n";
}
int main()
{
std::jthread myThread(workerThread); // create a jthread and start executing the workerThread function
// Do some other work while the thread is running
std::cout << "Main thread continues...\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
// Join the thread and wait for it to finish
myThread.join();
std::cout << "Main thread completed\n";
return 0;
}
In this example, we define a workerThread
function that simply sleeps for 2 seconds and then prints a message. In the main
function, we create a std::jthread
called myThread
and pass the workerThread
function as the constructor argument. This starts the execution of the workerThread
in a separate thread.
We then print a message from the main thread indicating that it continues its execution. After waiting for 1 second, we call myThread.join()
to join the std::jthread
and wait for it to finish. This means that the main thread will block until workerThread
completes its execution.
Finally, we print a message from the main thread indicating that it has completed.
Joining a std::jthread
allows us to synchronize the execution of multiple threads and ensures that the main thread waits for worker threads to finish before the program ends. This can be useful in scenarios where the main thread relies on the results or side effects of the worker thread’s computation.