Created
August 7, 2017 23:00
-
-
Save hamadu/829130ea55b68edc0cc8e276cdb2c9bc to your computer and use it in GitHub Desktop.
mutex
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 <unistd.h> | |
#include <stdio.h> | |
#include <pthread.h> | |
int x; | |
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER; | |
void add_x(int a) { | |
pthread_mutex_lock(&mut); | |
x += a; | |
pthread_mutex_unlock(&mut); | |
} | |
void* doit(void *arg) { | |
for (int i = 0 ; i < 100 ; i++) { | |
add_x(1); | |
} | |
printf("hello from another thread: %d\n", x); | |
return NULL; | |
} | |
int main(int argc, char* argv[]) { | |
for (int cur = 0 ; cur < 100 ; cur++) { | |
pthread_t thread; | |
pthread_create(&thread, NULL, *doit, NULL); | |
} | |
sleep(3); | |
printf("total: %d\n", x); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment