Advertisement
Jordimario

threadBase

Oct 8th, 2019
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. /*
  2.  * To change this license header, choose License Headers in Project Properties.
  3.  * To change this template file, choose Tools | Templates
  4.  * and open the template in the editor.
  5.  */
  6.  
  7. /*
  8.  * File:   main.cpp
  9.  * Author: docenti
  10.  *
  11.  * Created on 7 ottobre 2019, 13:26
  12.  */
  13.  
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <pthread.h>
  17. #include <math.h>
  18.  
  19. //#define EXIT_FAILURE    -1
  20. #define EXIT_SUCCESS    0
  21.  
  22. void* print_message_function( void *ptr );
  23.  
  24.  
  25. int main()
  26. {
  27.     const char *message1 = "Threadd 1";
  28.     const char *message2 = "Thread 2";
  29.         // Create independent threads each of which will execute 'print_message_function'
  30.     pthread_t thread1;
  31.     int cond1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
  32.     if (cond1 != 0) {
  33.            
  34.         fprintf(stderr,"Error - pthread_create() return code: %d\n", cond1);
  35.         exit(EXIT_FAILURE);
  36.     }
  37.    
  38.     pthread_t thread2;
  39.     int cond2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
  40.     if (cond2 != 0){
  41.         fprintf(stderr,"Error - pthread_create() return code: %d\n", cond2);
  42.         exit(EXIT_FAILURE);
  43.     }
  44.  
  45.     printf("pthread_create() for thread 1 returns: %d\n", cond1);
  46.     printf("pthread_create() for thread 2 returns: %d\n", cond2);
  47.  
  48.     // Attendiamo che i thread siano terminati prima di proseguire con la main.
  49.     // Se non aspettassimo, rischieremmo di eseguire la exit() che terminerrebbe
  50.     // il processo principale ma ache i thread prima che questi abbiano completato
  51.     // naturalmente la loro esecuzione.
  52.  
  53.     pthread_join(thread1, NULL);
  54.     pthread_join(thread2, NULL);
  55.  
  56.     exit(EXIT_SUCCESS);
  57. }
  58.  
  59. void *print_message_function( void *ptr )
  60. {
  61.     char *message;
  62.     message = (char *) ptr;
  63.     printf("%s \n", message);
  64.         return NULL;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement