Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <pthread.h>
- #include <time.h>
- // set a default number of threads to create
- #define NUM_THREADS 20
- struct timespec tp;
- int nThreads, sleepTime;
- /*** The thread function for each thread created in main, takes the identifier as an argument ***/
- void* sayHello ( void *ip ) {
- // sleep for some random number of seconds
- sleepTime = rand() % 2;
- sleep( sleepTime );
- int i = ( int ) ip;
- // print a message for each thread
- printf( "Hi I'm thread %d\n and my sleep time is %d\n", i, sleepTime );
- fflush( stdout );
- pthread_exit(NULL);
- }
- int main( int argc, char *argv[] ) {
- // loop counter
- int i;
- // ensure we have the correct number of args
- if( argc != 2 ) {
- printf( "Usage: ./nThreads nThreads\n" );
- fflush( stdout );
- return 1;
- }
- nThreads = atoi(argv[1]);
- // create an array of thread ids
- pthread_t threads[NUM_THREADS];
- // seed the srandom function using clock ticks
- srand ( clock_gettime( CLOCK_REALTIME, &tp ) );
- // print a message in main
- printf( "Creating %d threads in main...\n ", nThreads );
- fflush( stdout );
- // create the required number of threads, calling sayHello for each thread
- for( i = 0; i < nThreads; i++ ) {
- pthread_create( &threads[i], NULL, sayHello, (void*)i );
- }
- // wait for all threads to finish their execution
- for( i = 0; i < nThreads; i++ ) {
- pthread_join( threads[i], NULL );
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement