Created
May 16, 2013 16:21
-
-
Save ianliu/5592981 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
// compile with: gcc atomic-sum.c -lpthread | |
#define __STDC_FORMAT_MACROS | |
#include <pthread.h> | |
#include <stdio.h> | |
#include <time.h> | |
#include <unistd.h> | |
#include <inttypes.h> | |
uint64_t sum = 0; | |
static int n_threads = 4; | |
static int n_perthr = 1000000; | |
void *worker(void *arg) | |
{ | |
int i; | |
uint64_t s = 0; | |
for (i = 1; i <= n_perthr; i++) | |
__sync_fetch_and_add(&sum, 1); | |
// sum++; // Without any kind of lock, it will produce random outputs | |
return NULL; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
int i; | |
pthread_t threads[n_threads]; | |
for (i = 0; i < n_threads; i++) | |
pthread_create(&threads[i], NULL, worker, NULL); | |
for (i = 0; i < n_threads; i++) | |
pthread_join(threads[i], NULL); | |
uint64_t max = n_threads*n_perthr; | |
printf("Sum is %"PRIu64", should be %d*%d = %"PRIu64"\n", | |
sum, n_threads, n_perthr, max); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment