Example 2 Solution
Example 2 Solution
Example 2 Solution
To avoid the race condition, and to enforce storage ordering, you should serialize accesses to the shared data by one of the synchronization mechanisms that is enumerated above. This example, where multiple threads are competing for a shared resource, lends itself well to some form of lock. A solution employing a space location lock will be discussed, followed by an alternative solution using the Check Lock Value and Clear Lock Value.
THREAD A THREAD B
-------------------------------------- ------------------------------------
for (i=0; i<10; ++i) { for (i=0; i<10; ++i) {
/* Get an exclusive lock on the shared /* Get an exclusive lock on the shared
data. We go into a wait state until data. We go into a wait state until
the lock is granted. */ the lock is granted. */
locksl( LOCK_LOC, _LENR_LOCK ); locksl( LOCK_LOC, _LENR_LOCK );
/* Update the shared data */ /* Update the shared data */
data1 += 5; data1 += 4;
data2 += 10; data2 += 6;
/* Unlock the shared data */ /* Unlock the shared data */
unlocksl( LOCK_LOC, _LENR_LOCK ); unlocksl( LOCK_LOC, _LENR_LOCK );
} }
Restricting access to the shared data with a lock guarantees that only one thread will be able to access the data at a time. This solves the race condition. This solution also solves the storage access ordering concerns, since there is no longer an ordering dependency between two shared storage locations.