Advertisement
HmHimu

lab7.5

Nov 9th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.61 KB | None | 0 0
  1. /* Code for cond-hellothread.c */
  2.  
  3. #include <pthread.h>
  4.  
  5. #include <stdio.h>
  6.  
  7. /* This is the initial thread routine */
  8.  
  9. void* compute_thread (void*);
  10.  
  11. /* This is the lock for thread synchronization */
  12.  
  13. pthread_mutex_t my_sync;
  14.  
  15. /* This is the condition variable */
  16.  
  17. pthread_cond_t rx;
  18.  
  19.  
  20.  
  21. #define TRUE 1
  22.  
  23. #define FALSE 0
  24.  
  25. /* this is the Boolean predicate */
  26.  
  27. int thread_done = FALSE;
  28.  
  29. main( )
  30.  
  31. {
  32.  
  33. /* This is data describing the thread created */
  34.  
  35. pthread_t tid;
  36.  
  37. pthread_attr_t attr;
  38.  
  39. char hello[ ] = {"Hello, "};
  40.  
  41. char thread[ ] = {"thread"};
  42.  
  43. /* Initialize the thread attributes */
  44.  
  45. pthread_attr_init (&attr);
  46.  
  47. /* Initialize the mutex (default attributes) */
  48.  
  49. pthread_mutex_init (&my_sync, NULL);
  50.  
  51. /* Initialize the condition variable (default attr) */
  52.  
  53. pthread_cond_init (&rx, NULL);
  54.  
  55. /* Create another thread. ID is returned in &tid */
  56.  
  57. /* The last parameter is passed to the thread function */
  58.  
  59. pthread_create(&tid, &attr, compute_thread, hello);
  60.  
  61. /* wait until the thread does its work */
  62.  
  63. pthread_mutex_lock(&my_sync);
  64.  
  65. while (!thread_done)
  66.  
  67. pthread_cond_wait(&rx, &my_sync);
  68.  
  69. /* When we get here, the thread has been executed */
  70.  
  71. printf(thread);
  72.  
  73. printf("\n");
  74.  
  75. pthread_mutex_unlock(&my_sync);
  76.  
  77. exit(0);
  78.  
  79. }
  80.  
  81.  
  82. /* The thread to be run by create_thread */
  83.  
  84. void* compute_thread(void* dummy)
  85.  
  86. {
  87.  
  88. /* Lock the mutex - the cond_wait has unlocked it */
  89.  
  90. pthread_mutex_lock (&my_sync);
  91.  
  92. printf(dummy);
  93.  
  94. /* set the predicate and signal the other thread */
  95.  
  96. thread_done = TRUE;
  97.  
  98. pthread_cond_signal (&rx);
  99.  
  100. pthread_mutex_unlock (&my_sync);
  101.  
  102. return;
  103.  
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement