Advertisement
Guest User

Untitled

a guest
Jan 29th, 2013
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.59 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <pthread.h>
  3. #include <time.h>
  4.  
  5. // set a default number of threads to create
  6. #define NUM_THREADS 20
  7.  
  8. struct timespec tp;
  9. int nThreads, sleepTime;
  10.  
  11. /*** The thread function for each thread created in main, takes the identifier as an argument ***/
  12. void* sayHello ( void *ip ) {
  13.  
  14. // sleep for some random number of seconds
  15. sleepTime = rand() % 2;
  16. sleep( sleepTime );
  17.  
  18. int i = ( int ) ip;
  19.  
  20. // print a message for each thread
  21. printf( "Hi I'm thread %d\n and my sleep time is %d\n", i, sleepTime );
  22. fflush( stdout );
  23.  
  24. pthread_exit(NULL);
  25. }
  26.  
  27.  
  28. int main( int argc, char *argv[] ) {
  29.  
  30. // loop counter
  31. int i;
  32.  
  33.  
  34. // ensure we have the correct number of args
  35. if( argc != 2 ) {
  36. printf( "Usage: ./nThreads nThreads\n" );
  37. fflush( stdout );
  38. return 1;
  39. }
  40.  
  41.  
  42. nThreads = atoi(argv[1]);
  43.  
  44. // create an array of thread ids
  45. pthread_t threads[NUM_THREADS];
  46.  
  47. // seed the srandom function using clock ticks
  48. srand ( clock_gettime( CLOCK_REALTIME, &tp ) );
  49.  
  50.  
  51. // print a message in main
  52. printf( "Creating %d threads in main...\n ", nThreads );
  53. fflush( stdout );
  54.  
  55. // create the required number of threads, calling sayHello for each thread
  56. for( i = 0; i < nThreads; i++ ) {
  57. pthread_create( &threads[i], NULL, sayHello, (void*)i );
  58. }
  59.  
  60. // wait for all threads to finish their execution
  61. for( i = 0; i < nThreads; i++ ) {
  62. pthread_join( threads[i], NULL );
  63. }
  64.  
  65. return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement