Chapter: Multicore Application Programming For Windows, Linux, and Oracle Solaris : Synchronization and Data Sharing

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.

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 );

 

counter++;

 

pthread_mutex_unlock( &mutex );

 

}


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Multicore Application Programming For Windows, Linux, and Oracle Solaris : Synchronization and Data Sharing : Avoiding Data Races |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.