Browse Source

Added corrected main-race.c

Lorenz Bung 7 years ago
parent
commit
93732a171f
1 changed files with 5 additions and 0 deletions
  1. 5
    0
      hw8/simu1/main-race.c

+ 5
- 0
hw8/simu1/main-race.c View File

3
 #include "mythreads.h"
3
 #include "mythreads.h"
4
 
4
 
5
 int balance = 0;
5
 int balance = 0;
6
+pthread_mutex_t mut;
6
 
7
 
7
 void* worker(void* arg) {
8
 void* worker(void* arg) {
9
+    pthread_mutex_lock(&mut);
8
     balance++; // unprotected access
10
     balance++; // unprotected access
11
+    pthread_mutex_unlock(&mut);
9
     return NULL;
12
     return NULL;
10
 }
13
 }
11
 
14
 
12
 int main(int argc, char *argv[]) {
15
 int main(int argc, char *argv[]) {
13
     pthread_t p;
16
     pthread_t p;
14
     Pthread_create(&p, NULL, worker, NULL);
17
     Pthread_create(&p, NULL, worker, NULL);
18
+    pthread_mutex_lock(&mut);
15
     balance++; // unprotected access
19
     balance++; // unprotected access
20
+    pthread_mutex_unlock(&mut);
16
     Pthread_join(p, NULL);
21
     Pthread_join(p, NULL);
17
     return 0;
22
     return 0;
18
 }
23
 }

Loading…
Cancel
Save