Skip to content

Instantly share code, notes, and snippets.

@byyam
Created October 24, 2019 15:07
Show Gist options
  • Save byyam/1c51030e6d01682736b07dd1d225ca8a to your computer and use it in GitHub Desktop.
Save byyam/1c51030e6d01682736b07dd1d225ca8a to your computer and use it in GitHub Desktop.
pthread_mutex
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NLOOP 5000
pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
int counter;
void *doit(void *);
int main(int argc, char **argv)
{
pthread_t tidA, tidB;
pthread_create(&tidA, NULL, &doit, NULL);
pthread_create(&tidB, NULL, &doit, NULL);
pthread_join(tidA, NULL);
pthread_join(tidB, NULL);
return 0;
}
void *doit(void *vptr)
{
int i, val;
for (i = 0; i < NLOOP; i++) {
pthread_mutex_lock(&counter_mutex);
val = counter;
printf("%x: %d\n", (unsigned int)pthread_self(), val + 1);
counter = val + 1;
pthread_mutex_unlock(&counter_mutex);
}
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment