daily pastebin goal
76%
SHARE
TWEET

Untitled

a guest Sep 22nd, 2018 55 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Includes */
  2. #include <unistd.h>     /* Symbolic Constants */
  3. #include <sys/types.h>  /* Primitive System Data Types */
  4. #include <errno.h>      /* Errors */
  5. #include <stdio.h>      /* Input/Output */
  6. #include <stdlib.h>     /* General Utilities */
  7. #include <pthread.h>    /* POSIX Threads */
  8. #include <string.h>     /* String handling */
  9.  
  10. /* prototype for thread routine */
  11. void print_message_function ( void *ptr );
  12.  
  13. /* struct to hold data to be passed to a thread
  14.    this shows how multiple data items can be passed to a thread */
  15. typedef struct str_thdata
  16. {
  17.     int thread_no;
  18.     char message[100];
  19. } thdata;
  20.  
  21. int main()
  22. {
  23.     pthread_t thread1, thread2;  /* thread variables */
  24.     thdata data1, data2;         /* structs to be passed to threads */
  25.    
  26.     /* initialize data to pass to thread 1 */
  27.     data1.thread_no = 1;
  28.     strcpy(data1.message, "Hello!");
  29.  
  30.     /* initialize data to pass to thread 2 */
  31.     data2.thread_no = 2;
  32.     strcpy(data2.message, "Hi!");
  33.    
  34.     /* create threads 1 and 2 */    
  35.     pthread_create (&thread1, NULL, (void *) &print_message_function, (void *) &data1);
  36.     pthread_create (&thread2, NULL, (void *) &print_message_function, (void *) &data2);
  37.  
  38.     /* Main block now waits for both threads to terminate, before it exits
  39.        If main block exits, both threads exit, even if the threads have not
  40.        finished their work */
  41.     pthread_join(thread1, NULL);
  42.     pthread_join(thread2, NULL);
  43.              
  44.     /* exit */  
  45.     exit(0);
  46. } /* main() */
  47.  
  48. /**
  49.  * print_message_function is used as the start routine for the threads used
  50.  * it accepts a void pointer
  51. **/
  52. void print_message_function ( void *ptr )
  53. {
  54.     thdata *data;            
  55.     data = (thdata *) ptr;  /* type cast to a pointer to thdata */
  56.    
  57.     /* do the work */
  58.     printf("Thread %d says %s \n", data->thread_no, data->message);
  59.    
  60.     pthread_exit(0); /* exit */
  61. } /* print_message_function ( void *ptr ) */
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top