Skip to content

Instantly share code, notes, and snippets.

@5kg
Created January 24, 2013 05:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 5kg/4617935 to your computer and use it in GitHub Desktop.
Save 5kg/4617935 to your computer and use it in GitHub Desktop.
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <string.h>
#include <assert.h>
#define tic() do { struct timespec ts_start, ts_end; clock_gettime(CLOCK_MONOTONIC, &ts_start)
#define toc() clock_gettime(CLOCK_MONOTONIC, &ts_end); \
printf("%lfs\n", (ts_end.tv_sec - ts_start.tv_sec) + (double)(ts_end.tv_nsec - ts_start.tv_nsec)/1e9); } \
while (0)
#define NUM_THREADS 4
#define N 65536
#define THRESHOLD 130124
void* foo(void *);
void* bar(void *);
int* num;
int s[NUM_THREADS];
int main()
{
pthread_t threads[NUM_THREADS];
int ans, ANS = 0;
num = (int*) malloc(sizeof(int) * N);
srand(42);
for (int i = 0; i < N; ++i) {
num[i] = rand() % 100;
ANS += num[i];
}
memset(s, 0, sizeof(s));
ans = 0;
tic();
for (int i = 0; i < NUM_THREADS; ++i)
pthread_create(threads + i, NULL, foo, s + i);
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
ans += s[i];
}
toc();
assert(ans == ANS);
memset(s, 0, sizeof(s));
ans = 0;
tic();
for (int i = 0; i < NUM_THREADS; ++i)
pthread_create(threads + i, NULL, bar, s + i);
for (int i = 0; i < NUM_THREADS; ++i) {
pthread_join(threads[i], NULL);
ans += s[i];
}
toc();
assert(ans == ANS);
return 0;
}
void* foo(void* ptr)
{
int* r = (int*) ptr;
for (int i = (r - s); i < N; i += NUM_THREADS)
*r += num[i];
return NULL;
}
void* bar(void* ptr)
{
int* r = (int*) ptr;
int idx = r - s;
int block = N/NUM_THREADS;
int start = idx * block, end = start + block;
for (int i = start; i < end; ++i)
*r += num[i];
return NULL;
}
@VexZy
Copy link

VexZy commented Feb 27, 2021

not working 👎

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment