c:c_threads:transfer_ownership_of_threads_at_runtime
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revision | ||
c:c_threads:transfer_ownership_of_threads_at_runtime [2021/03/05 11:38] – peter | c:c_threads:transfer_ownership_of_threads_at_runtime [2021/06/09 11:07] (current) – peter | ||
---|---|---|---|
Line 1: | Line 1: | ||
====== C - C++ Threads - Transfer ownership of threads at runtime ====== | ====== C - C++ Threads - Transfer ownership of threads at runtime ====== | ||
- | Thestd::thread object | + | **std:: |
+ | |||
+ | ---- | ||
+ | |||
+ | ===== Problem ===== | ||
+ | |||
+ | <code cpp> | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | #include < | ||
+ | |||
+ | void Func1() | ||
+ | { | ||
+ | std:: | ||
+ | std::cout << " | ||
+ | } | ||
+ | |||
+ | int main() | ||
+ | { | ||
+ | std::thread t1(Func1); | ||
+ | t1.join(); | ||
+ | |||
+ | std::cout << " | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | </ | ||
+ | |||
+ | <WRAP info> | ||
+ | **NOTE: | ||
+ | |||
+ | This shows that the main() | ||
+ | |||
+ | A **join** blocks the thread that called it; in this example the thread that call the t1 thread is the main() thread. | ||
+ | |||
+ | This may result in the application freezing. | ||
+ | |||
+ | </ | ||
- | std::move can be called to move the ownership of the underlying resource from one std::thread object to another. | ||
---- | ---- | ||
- | ===== Example | + | ===== Solution |
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. | 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. | ||
Line 32: | Line 69: | ||
{ | { | ||
std::thread t1(Func1); | std::thread t1(Func1); | ||
+ | |||
+ | // Pass the responsibility of monitoring the t1 thread to t2. | ||
std::thread t2(Func2, std:: | std::thread t2(Func2, std:: | ||
// Do a bunch of other processing without waiting for t1 to finish. | // 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. | ||
- | |||
std::cout << " | std::cout << " | ||
Line 47: | Line 84: | ||
<WRAP important> | <WRAP important> | ||
- | **NOTE: | + | **NOTE: |
- | + | ||
- | This may result in the application freezing. | + | |
- | + | ||
- | To overcome this issue, ownership of the thread | + | |
- | Here | + | Ownership of the t1 thread is passed to a different thread, in this example, t2, allowing the main() thread to not be blocked. |
</ | </ |
c/c_threads/transfer_ownership_of_threads_at_runtime.1614944295.txt.gz · Last modified: 2021/03/05 11:38 by peter