Created
October 2, 2013 04:21
-
-
Save Keith-S-Thompson/6789119 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/* | |
* Test program based on code in the Wikipedia POSIX Threads | |
* article, https://en.wikipedia.org/wiki/POSIX_Threads. | |
* | |
* Demo for http://stackoverflow.com/q/19128948/827263 | |
*/ | |
#include <pthread.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <assert.h> | |
#define NUM_THREADS 5 | |
long getTimeMilliSecs() | |
{ | |
struct timeval tempTime; | |
gettimeofday(&tempTime, NULL); | |
long retVal = 1000000*tempTime.tv_sec + tempTime.tv_usec; | |
return retVal; | |
} | |
void *TaskCode(void *argument) | |
{ | |
int tid; | |
tid = *((int *) argument); | |
printf("thread %d, getTimeMilliSecs() = %ld\n", tid, getTimeMilliSecs()); | |
/* optionally: insert more useful stuff here */ | |
return NULL; | |
} | |
int main(void) | |
{ | |
pthread_t threads[NUM_THREADS]; | |
int thread_args[NUM_THREADS]; | |
int rc, i; | |
printf("main, getTimeMilliSecs() = %ld\n", getTimeMilliSecs()); | |
/* create all threads */ | |
for (i=0; i<NUM_THREADS; ++i) { | |
thread_args[i] = i; | |
printf("In main: creating thread %d\n", i); | |
rc = pthread_create(&threads[i], NULL, TaskCode, (void *) &thread_args[i]); | |
assert(0 == rc); | |
} | |
/* wait for all threads to complete */ | |
for (i=0; i<NUM_THREADS; ++i) { | |
rc = pthread_join(threads[i], NULL); | |
assert(0 == rc); | |
} | |
exit(EXIT_SUCCESS); | |
} |
This file contains hidden or 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
main, getTimeMilliSecs() = 1380687691732016 | |
In main: creating thread 0 | |
In main: creating thread 1 | |
In main: creating thread 2 | |
thread 0, getTimeMilliSecs() = 1380687691732198 | |
In main: creating thread 3 | |
thread 1, getTimeMilliSecs() = 1380687691732206 | |
thread 2, getTimeMilliSecs() = 1380687691732290 | |
In main: creating thread 4 | |
thread 3, getTimeMilliSecs() = 1380687691732306 | |
thread 4, getTimeMilliSecs() = 1380687691732331 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment