Skip to content

Instantly share code, notes, and snippets.

@soramichi
Created August 24, 2016 06:00
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#if defined(SPIN)
pthread_spinlock_t m;
#else
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
#endif
volatile unsigned long shared_val = 0;
int loop;
void* func(void* arg){
int i;
for(i=0; i<loop; i++){
#if defined(SPIN)
pthread_spin_lock(&m);
#else
pthread_mutex_lock(&m);
#endif
shared_val++;
#if defined(SPIN)
pthread_spin_unlock(&m);
#else
pthread_mutex_unlock(&m);
#endif
}
}
int main(int argc, char* argv[]){
if(argc >= 2){
loop = atoi(argv[1]);
}
else{
loop = 1000;
}
#if defined(SPIN)
pthread_spin_init(&m, PTHREAD_PROCESS_SHARED);
#endif
printf("thread acquire and release a lock %d times\n", loop);
pthread_t pid1, pid2;
pthread_create(&pid1, NULL, func, NULL);
pthread_create(&pid2, NULL, func, NULL);
pthread_join(pid1, NULL);
pthread_join(pid2, NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment