d1cor

thread4.c

Oct 25th, 2017
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.02 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <assert.h>
  5.  
  6. #define NUM_THREADS     5
  7.  
  8. void *task_code(void *argument)
  9. {
  10.    int tid;
  11.  
  12.    tid = *((int *) argument);
  13.    printf("Hello World! It's me, thread %d!\n", tid);
  14.  
  15.    /* optionally: insert more useful stuff here */
  16.  
  17.    return NULL;
  18. }
  19.  
  20. int main(void)
  21. {
  22.    pthread_t threads[NUM_THREADS];
  23.    int thread_args[NUM_THREADS];
  24.    int rc, i;
  25.  
  26.    // create all threads one by one
  27.    for (i=0; i<NUM_THREADS; ++i) {
  28.       thread_args[i] = i;
  29.       printf("In main: creating thread %d\n", i);
  30.       rc = pthread_create(&threads[i], NULL, task_code, (void *) &thread_args[i]);
  31.       assert(0 == rc);
  32.    }
  33.  
  34.    // wait for each thread to complete
  35.    for (i=0; i<NUM_THREADS; ++i) {
  36.       // block until thread i completes
  37.       rc = pthread_join(threads[i], NULL);
  38.       printf("In main: thread %d is complete\n", i);
  39.       assert(0 == rc);
  40.    }
  41.  
  42.    printf("In main: All threads completed successfully\n");
  43.    exit(EXIT_SUCCESS);
  44. }
Add Comment
Please, Sign In to add comment