Saturday, October 25, 2014

Unix Prog: Thread Synchronization

1. Thread Synchronization Examples
If the "write" operation needs multiple memory cycles, then when multiple threads are operating same variables, the thread 2 may read inconsistent value.

At above example, thread 1 is reading the variable, then writing the new value. After the first step of write, at this time, thread 2 read the value of the variable, which is a inconsistent value.

Adding the lock can solve the problem:
Every time when a thread needs to access the thread, it needs to acquire the lock, after the operation is done, thread needs to release the lock to let other threads operate the lock.

At above example, thread 2 acquire the lock firstly to read the variable, then release the lock. And then thread 1 acquire the lock to read and write a new value, during this period, thread 2 can not read the value of variable until thread 1 release its lock.

When multiple threads are modifying the variable value at the same time, inconsistency may also occur:

At above example, both thread 1 and thread 2 are going to increase the i's value, so we expect i should be increased by 2, but in the end i is creased by 1.

No comments:

Post a Comment