fork download
  1. // buffer.c
  2. // Bounded-buffer Producer/Consumer problem with semaphores
  3. #include <pthread.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. void* func(void* arg)
  8. {
  9. // detach the current thread
  10. // from the calling thread
  11. pthread_detach(pthread_self());
  12.  
  13. printf("Inside the thread\n");
  14.  
  15. // exit the current thread
  16. pthread_exit(NULL);
  17. }
  18.  
  19. void fun()
  20. {
  21. pthread_t ptid;
  22.  
  23. // Creating a new thread
  24. pthread_create(&ptid, NULL, &func, NULL);
  25. printf("This line may be printed"
  26. " before thread terminates\n");
  27.  
  28. // The following line terminates
  29. // the thread manually
  30. // pthread_cancel(ptid);
  31.  
  32. // Compare the two threads created
  33. if(pthread_equal(ptid, pthread_self()))
  34. printf("Threads are equal\n");
  35. else
  36. printf("Threads are not equal\n");
  37.  
  38. // Waiting for the created thread to terminate
  39. pthread_join(ptid, NULL);
  40.  
  41. printf("This line will be printed"
  42. " after thread ends\n");
  43.  
  44. pthread_exit(NULL);
  45. }
  46.  
  47. // Driver code
  48. int main()
  49. {
  50. fun();
  51. return 0;
  52. }
Success #stdin #stdout 0s 5284KB
stdin
Standard input is empty
stdout
This line may be printed before thread terminates
Threads are not equal
Inside the thread
This line will be printed after thread ends