6. Exercises
-
See the book for exercises using helgrind,
i.e.
valgrind --tool=helgrind
Example: Q1,2 main-race.c
1 #include <stdio.h> 2 3 #include "common_threads.h" 4 5 int balance = 0; 6 7 void* worker(void* arg) { 8 balance++; // unprotected access 9 return NULL; 10 } 11 12 int main(int argc, char *argv[]) { 13 pthread_t p; 14 Pthread_create(&p, NULL, worker, NULL); 15 balance++; // unprotected access 16 Pthread_join(p, NULL); 17 return 0; 18 } $ valgrind --tool=helgrind ./main-race ... ==25147== Possible data race during read of size 4 at 0x30A040 by thread #1 ==25147== Locks held: none ... ==25147== This conflicts with a previous write of size 4 by thread #2 ==25147== Locks held: none ...
Fix using a lock.