Last active
June 4, 2021 05:34
-
-
Save gunavaran/ce849a0bc3958091f5b72be7539a715f to your computer and use it in GitHub Desktop.
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
// | |
// Created by gunavaran on 6/2/21. | |
// | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <pthread.h> | |
#define NUM_THREADS 4 | |
#define NUM_ITERATIONS 1000000000 | |
volatile int count; | |
pthread_mutex_t lock; | |
//using mutex which is a lock-based approach | |
void *mutex_increment() { | |
for (int i = 0; i < NUM_ITERATIONS / NUM_THREADS; i++) { | |
pthread_mutex_lock(&lock); | |
count++; | |
pthread_mutex_unlock(&lock); | |
} | |
} | |
//using an atomic built in of GCC, a lock-free approach | |
void *fetch_and_add_increment() { | |
for (int i = 0; i < NUM_ITERATIONS / NUM_THREADS; i++) { | |
__sync_fetch_and_add(&count, 1); | |
} | |
} | |
int main() { | |
pthread_t threads[NUM_THREADS]; | |
int rc; | |
void *status; | |
for (int i = 0; i < NUM_THREADS; i++) { | |
rc = pthread_create(&threads[i], NULL, mutex_increment, NULL); | |
if (rc) { | |
printf("ERROR; return code from pthread_create() is %d\n", rc); | |
exit(-1); | |
} | |
} | |
for (int i = 0; i < NUM_THREADS; i++) { | |
rc = pthread_join(threads[i], &status); | |
} | |
printf("Total %d \n", count); | |
pthread_exit(NULL); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment