Copied Value
Explore the copied value pattern in concurrency to prevent race conditions by passing thread data as a copy rather than a reference. Understand how this technique eliminates data races and lifetime issues in multithreaded C++ programs, enhancing safe parallel execution.
We'll cover the following...
In parallel programming, we can come across situations where different threads need the same resource. This can result in a race condition as the two threads compete for the same resource. To avoid consistency issues, we need to synchronize it. This problem can be solved using OS concepts like mutex locks, but those are not covered in the scope of this course. In this lesson, we’ll learn how the copied value pattern can solve our synchronization problem.
According to the copy value pattern, the thread should receive its data by copy and not by reference.
Let’s take a look at its code.
Explanation
-
Line 29: We initialized a variable
shared, which will be shared across the threads. -
Lines 31–33: We created three threads:
t1: This calls thebyCopyfunction withsharedas the argument. This will pass the copy of the shared variable to the function.t2: This calls thebyReferencefunction and will pass thesharedvariable through reference.t3: This calls thebyConstReferencefunction with the constant reference of thesharedvariable.
-
Line 35: The value of the shared variable
sharedis changed totrue. -
Lines 37–39: We used
join, due to which the main thread waits for other child threads to finish execution.
Each time we click the “Run” button, we should see different outputs due to race-condition among the threads, which causes data inconsistencies.
Advantage
- Using the copied value makes it possible to eliminate data races and lifetime problems.