Data Race in my last example

I got some polite email from Yuan Lin pointing out that my example program had a data race in it. He suggested that I should change my food_on_table function as follows to avoid the race.

From

int food_on_table() {
   pthread_mutex_lock(&foodlock);
   if (food>0) {
      food--;
   }
   pthread_mutex_unlock(&foodlock);
   return food;
}
to
int food_on_table() {
   int current_food;
   pthread_mutex_lock(&foodlock);
   current_food = food;
   if (food>0) {
      food--;
      current_food = food;
   }
   pthread_mutex_unlock(&foodlock);
   return current_food;
} 
Good catch, Yuan! Thanks for the tip. Next time I'll use our Data Race Detection Tool.
Comments:

Post a Comment:
Comments are closed for this entry.
About

Chris Quenelle

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today