Created
February 21, 2021 22:57
-
-
Save csfelipe/42741e6867a2405f21c9aa469e625a90 to your computer and use it in GitHub Desktop.
This is the C program with mutex displayed in the lecture "6.2.4. Example of race condition" in the UC3M course "Cybersecurity: A hands-on approach"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
void *add_function(); | |
int addMul = 0; | |
pthread_mutex_t lock; | |
main() { | |
pthread_t thread; | |
pthread_mutex_init(&lock, NULL); | |
int ret[70]; | |
int i=0; | |
for (i=0; i<70; i++) { | |
ret[i] = pthread_create(&thread, NULL, add_function, NULL); | |
} | |
pthread_exit(NULL); | |
printf("RESULT %d\n", addMul); | |
exit(EXIT_SUCCESS); | |
} | |
void *add_function() { | |
pthread_mutex_lock(&lock); | |
int i = 0; | |
for (i=0;i<10;i++) { | |
int b = 0; | |
while (b<400) { | |
addMul++; | |
b++; | |
} | |
printf("Result of adding i=0 | %d\n", addMul); | |
pthread_mutex_unlock(&lock); | |
pthread_exit(NULL); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment