Skip to content

Instantly share code, notes, and snippets.

@aburan28
Created January 19, 2017 23:16
Show Gist options
  • Save aburan28/2d1ce09b2b1d7b949d136ac2b62f2b49 to your computer and use it in GitHub Desktop.
Save aburan28/2d1ce09b2b1d7b949d136ac2b62f2b49 to your computer and use it in GitHub Desktop.
void iter_threads(int start, int end, void (*func)(int n))
{
int n = start;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *thread_body(void *ptr)
{
double start = now();
for (;;) {
pthread_mutex_lock( &mutex );
int i = (n)++;
pthread_mutex_unlock( &mutex );
if (i >= end)
break;
func(i);
}
fprintf(stderr, "(ok %0.3fs)", now()-start);
return NULL;
}
pthread_t thread_id[NTHREADS];
for (int i=0; i<NTHREADS; i++)
pthread_create(&thread_id[i], NULL, thread_body, NULL);
for (int i=0; i<NTHREADS; i++)
pthread_join(thread_id[i], NULL);
fprintf(stderr, "\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment