Created
March 11, 2012 03:57
-
-
Save storborg/2014932 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
#include <pthread.h> | |
#include <stdio.h> | |
#define NUM_WAITING_THREADS 20 | |
#define NUM_WORKING_THREADS 20 | |
pthread_mutex_t quux; | |
void waste_some_time(int cycles) { | |
int i, v; | |
for(i=0; i < cycles; i++) { | |
v = i^2; | |
} | |
} | |
void *waiting_thread(void *threadid) { | |
long tid; | |
tid = (long)threadid; | |
printf("%ld: this is a waiting thread, trying to lock\n", tid); | |
pthread_mutex_lock(&quux); | |
printf("%ld: got my lock, unlocking and exiting\n", tid); | |
pthread_mutex_unlock(&quux); | |
pthread_exit(NULL); | |
} | |
void *working_thread(void *threadid) { | |
long tid; | |
tid = (long)threadid; | |
printf("%ld: this is a working thread\n", tid); | |
waste_some_time(100000000); | |
pthread_exit(NULL); | |
} | |
int main (int argc, char *argv[]) | |
{ | |
pthread_t threads[NUM_WAITING_THREADS + NUM_WORKING_THREADS]; | |
int rc; | |
long t; | |
pthread_mutex_init(&quux, NULL); | |
pthread_mutex_lock(&quux); | |
for(t=0; t < NUM_WAITING_THREADS; t++){ | |
printf("In main: creating waiting thread %ld\n", t); | |
rc = pthread_create(&threads[t], NULL, waiting_thread, (void *)t); | |
if (rc){ | |
printf("ERROR; return code from pthread_create() is %d\n", rc); | |
exit(-1); | |
} | |
} | |
for(; t < NUM_WAITING_THREADS + NUM_WORKING_THREADS; t++) { | |
printf("In main: creating working thread %ld\n", t); | |
rc = pthread_create(&threads[t], NULL, working_thread, (void *)t); | |
if (rc){ | |
printf("ERROR; return code from pthread_create() is %d\n", rc); | |
exit(-1); | |
} | |
} | |
printf("wasting some time in main thread\n"); | |
waste_some_time(100000000); | |
printf("main thread done, unlocking\n"); | |
pthread_mutex_unlock(&quux); | |
pthread_mutex_destroy(&quux); | |
pthread_exit(NULL); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment