Skip to content

Instantly share code, notes, and snippets.

@s8sg
Created November 8, 2017 07:36
Show Gist options
  • Save s8sg/97a3eaf5432ceff0530e6e386bf24e6c to your computer and use it in GitHub Desktop.
Save s8sg/97a3eaf5432ceff0530e6e386bf24e6c to your computer and use it in GitHub Desktop.
Lockless Counter
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
#include<stdbool.h>
#include<time.h>
#define SYNC_INCREASE_COUNT(var_ref, temp) while(true) {temp=*var_ref; if(__sync_bool_compare_and_swap(var_ref, temp, (temp + 1))) {break;}pthread_yield();}
#define sync_increase_count(var_ref, mutex_ref) pthread_mutex_lock(mutex_ref);*var_ref=*var_ref+1;pthread_mutex_unlock(mutex_ref);
int counter = 0;
pthread_mutex_t mutex;
static void * incrementer(void *param) {
int i = 0;
int *var = (int*)param;
for (i=0; i<200000000; i++) {
sync_increase_count(var, &mutex);
}
}
static void * e_incrementer(void *param) {
int i = 0;
int *var = (int*)param;
int temp;
for (i=0; i<200000000; i++) {
SYNC_INCREASE_COUNT(var, temp);
}
}
int main(int argc, char **argv) {
pthread_t thread[3];
pthread_t e_thread[3];
char *b;
int i;
time_t start_t, end_t;
double diff_t;
pthread_mutex_init(&mutex, NULL);
time(&start_t);
for (i=0; i<3; i++) {
pthread_create(&thread[i], NULL, incrementer, &counter);
}
for (i=0; i<3; i++) {
pthread_join(thread[i], (void**)&b);
}
time(&end_t);
diff_t = difftime(end_t, start_t);
printf("Normal Counter: %d, diff: %f\n", counter, diff_t);
counter = 0;
time(&start_t);
for (i=0; i<3; i++) {
pthread_create(&e_thread[i], NULL, e_incrementer, &counter);
}
for (i=0; i<3; i++) {
pthread_join(e_thread[i], (void**)&b);
}
time(&end_t);
diff_t = difftime(end_t, start_t);
printf("Lockless Counter: %d, diff: %f\n", counter, diff_t);
}
/* $ gcc lockless_counter.c -lpthread
* $ ./a.out
* Normal Counter: 600000000, diff: 41.000000
* Lockless Counter: 600000000, diff: 19.000000
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment