Created
October 20, 2016 04:35
-
-
Save dryman/e65db7fe961e0f3929c8230dcb14c3fc to your computer and use it in GitHub Desktop.
thread local bench
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
// gcc -O2 -Wall -pthread tls_bench.c -o tls_bench | |
// ./tls_bench <num_threads> <loop> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdint.h> | |
#include <pthread.h> | |
#include <assert.h> | |
#include <stdatomic.h> | |
__thread int tls = -1; | |
_Atomic uint32_t counter[8] = {0}; | |
_Atomic uint32_t round_robin = 0; | |
void* counter_thread(void *args) | |
{ | |
const int loop = *(int*)args; | |
if (tls == -1) | |
tls = atomic_fetch_add_explicit(&round_robin, 1, memory_order_relaxed) % 8; | |
printf("tls is %d\n", tls); | |
for (int i = 0; i < loop; i++) | |
atomic_fetch_add_explicit(&counter[tls], 1, memory_order_relaxed); | |
return NULL; | |
} | |
int main(int argc, char** argv) | |
{ | |
assert(argc == 3); | |
int num_threads = atoi(argv[1]); | |
int loop = atoi(argv[2]); | |
pthread_t *threads = alloca(sizeof(pthread_t)*num_threads); | |
for (int i = 0; i < num_threads; i++) | |
assert(!pthread_create(&threads[i], NULL, counter_thread, &loop)); | |
for (int i = 0; i < num_threads; i++) | |
assert(!pthread_join(threads[i], NULL)); | |
for (int i = 0; i < 8; i++) | |
printf("Atomic counter[%d] = %d\n", i, | |
atomic_load_explicit(&counter[i], memory_order_relaxed)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment