MultiThreading
|
To add synchronization add a mutex to the code and "lock" it before accessing the data:
The call to the changed access function remains basically the same:
Running the program leads to an output similar to:
___________ ABCDEFGHIJK ABCDEFGHIJK ___________ ___________ ABCDEFGHIJK ABCDEFGHIJK ABCDEFGHIJK ABCDEFGHIJK ABCDEFGHIJK ___________ ___________ ___________ ABCDEFGHIJK __________ _ ABCDEFGHIJK ___________ ABCDEFGHIJK ___________ ABCDEFGHI JK ___________ ___________ ___________ ABCDEFGHIJK ABCDEFGHI JK ABCDEFGHIJK ABCDEFGHIJK ABCDEFGHIJK ___________ _________
Now it is guaranteed that the variable only has one of the defined values. Because of multi threading it remains random behaviour how many reads will result in the same value before it changes.