Advertisement
Guest User

hello_pthread

a guest
Sep 23rd, 2014
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.70 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <pthread.h>
  5.  
  6.  
  7. #define MAX_THREADS 5
  8.  
  9.  
  10. void *print_message(void *message)
  11. {
  12.     const char *msg = (char *) message;
  13.     printf("%s!\n", msg);
  14.     free(message);
  15.     pthread_exit(NULL);
  16. }
  17.  
  18.  
  19. int main(int argc, char *argv[])
  20. {
  21.     const char *fmt = "Here is %d";
  22.     pthread_t threads[MAX_THREADS];
  23.     char *message;
  24.     int i;
  25.  
  26.     for(i = 0; i < MAX_THREADS; ++i) {
  27.         message = malloc(sizeof(char) * strlen(fmt));
  28.         sprintf(message, fmt, i);
  29.         if (pthread_create(&threads[i], NULL, print_message,
  30.                 (void *) message)) {
  31.             fprintf(stderr,
  32.                 "[ERROR]: while creating thread %d\n", i);
  33.             exit(EXIT_FAILURE);
  34.         }
  35.     }
  36.  
  37.     return EXIT_SUCCESS;
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement