Avoiding Data Races
Although it can be hard to identify data races, avoiding them can be very simple: Make sure that only one thread can update the variable at a time. The easiest way to do this is to place a synchronization lock around all accesses to that variable and ensure that before referencing the variable, the thread must acquire the lock. Listing 4.6 shows a modified version of the code. This version uses a mutex lock, described in more detail in the next section, to protect accesses to the variable counter. Although this ensures the correct-ness of the code, it does not necessarily give the best performance, as will be discussed in later chapters.
Listing 4.6 Code Modified to Avoid Data Races
void * func( void * params )
pthread_mutex_lock( &mutex );
pthread_mutex_unlock( &mutex );
Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.