c:c_threads:transfer_ownership_of_threads_at_runtime
This is an old revision of the document!
C - C++ Threads - Transfer ownership of threads at runtime
Thestd::thread object owns the current thread of execution.
std::move can be called to move the ownership of the underlying resource from one std::thread object to another.
Example
To not have to wait for a thread to finish, pass the thread to another function which will wait for the thread to finish and execute some action once the execution is done.
#include <iostream> #include <string> #include <thread> #include <functional> void Func1() { std::this_thread::sleep_for(std::chrono::milliseconds(5000)); std::cout << "Finished Func1"<< std::endl; } void Func2(std::thread t1) { t1.join(); std::cout << "Finished Func2" << std::endl; } int main() { std::thread t1(Func1); std::thread t2(Func2, std::move(t1)); // Do a bunch of other processing without waiting for t1 to finish. // Instead now the responsibility of monitoring the t1 thread is passed to t2. // Finally wait for t2 to finish. t2.join(); return 0; }
c/c_threads/transfer_ownership_of_threads_at_runtime.1614943782.txt.gz · Last modified: 2021/03/05 11:29 by peter