User Tools

Site Tools


c:c_threads:transfer_ownership_of_threads_at_runtime

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
c:c_threads:transfer_ownership_of_threads_at_runtime [2021/03/05 11:47] peterc: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 ======
  
-std::move can be called to move the ownership of the underlying thread resource from one std::thread object to another.+**std::move** can be called to move the ownership of the underlying thread resource from one std::thread object to another.
  
 ---- ----
Line 30: Line 30:
 </code> </code>
  
 +<WRAP info>
 **NOTE:**  The **Continue Main** message is only displayed once the function Func1 finishes. **NOTE:**  The **Continue Main** message is only displayed once the function Func1 finishes.
  
 This shows that the main() thread is blocked until the t1 thread completes. This shows that the main() thread is blocked until the t1 thread completes.
 +
 +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.
 +
 +</WRAP>
 +
  
 ---- ----
Line 61: 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::move(t1));   std::thread t2(Func2, std::move(t1));
  
   // 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 << "Continue Main" << std::endl;   std::cout << "Continue Main" << std::endl;
  
Line 78: Line 86:
 **NOTE:**  Notice that now the **Continue Main** message is displayed even before the thread function finishes. **NOTE:**  Notice that now the **Continue Main** message is displayed even before the thread function finishes.
  
-A join() blocks the thread that called it, in this example the main() thread. +Ownership of the t1 thread is passed to a different thread, in this example, t2, allowing the main() thread to not be blocked.
- +
-This may result in the application freezing. +
- +
-To overcome this issue, ownership of the thread is passed to a different thread, in this example, t2, allowing the main() thread to not be blocked.+
  
 </WRAP> </WRAP>
c/c_threads/transfer_ownership_of_threads_at_runtime.1614944862.txt.gz · Last modified: 2021/03/05 11:47 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki