fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <unistd.h> // For sleep function
  5.  
  6. void *print_message_function(void *ptr);
  7.  
  8. int main()
  9. {
  10. pthread_t thread1, thread2;
  11. char *message1 = "Thread 1";
  12. char *message2 = "Thread 2";
  13. int iret1, iret2;
  14.  
  15. /* Create independent threads each of which will execute function */
  16. iret1 = pthread_create(&thread1, NULL, print_message_function, (void *)message1);
  17.  
  18. // Introduce a delay to ensure thread1 has started (not reliable for all cases)
  19. sleep(1); // Sleep for 1 second
  20.  
  21. iret2 = pthread_create(&thread2, NULL, print_message_function, (void *)message2);
  22.  
  23. /* Wait till threads are complete before main continues. Unless we */
  24. /* wait we run the risk of executing an exit which will terminate */
  25. /* the process and all threads before the threads have completed. */
  26. pthread_join(thread1, NULL);
  27. pthread_join(thread2, NULL);
  28.  
  29. printf("Thread 1 returns: %d\n", iret1);
  30. printf("Thread 2 returns: %d\n", iret2);
  31.  
  32. exit(0);
  33. }
  34.  
  35. void *print_message_function(void *ptr)
  36. {
  37. char *message;
  38. message = (char *)ptr;
  39. printf("%s\n", message);
  40. return NULL;
  41. }
  42.  
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Thread 1
Thread 2
Thread 1 returns: 0
Thread 2 returns: 0