Skip to content

Instantly share code, notes, and snippets.

@hamadu
Created August 7, 2017 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamadu/829130ea55b68edc0cc8e276cdb2c9bc to your computer and use it in GitHub Desktop.
Save hamadu/829130ea55b68edc0cc8e276cdb2c9bc to your computer and use it in GitHub Desktop.
mutex
#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