fork download
  1. #include <stdio.h>
  2. #include <pthread.h>
  3.  
  4. pthread_mutex_t lock;
  5. pthread_cond_t condition;
  6.  
  7. void* waiting_thread(void* arg) {
  8. pthread_mutex_lock(&lock);
  9. printf("Waiting for signal...\n");
  10. pthread_cond_wait(&condition, &lock);
  11. printf("Received signal!\n");
  12. pthread_mutex_unlock(&lock);
  13. return NULL;
  14. }
  15.  
  16. void* signaling_thread(void* arg) {
  17. pthread_mutex_lock(&lock);
  18. printf("Sending signal...\n");
  19. pthread_cond_signal(&condition);
  20. pthread_mutex_unlock(&lock);
  21. return NULL;
  22. }
  23.  
  24. int main() {
  25. pthread_t thread1, thread2;
  26. pthread_mutex_init(&lock, NULL);
  27. pthread_cond_init(&condition, NULL);
  28.  
  29. pthread_create(&thread1, NULL, waiting_thread, NULL);
  30. sleep(1); // Ensuring the waiting thread executes first
  31. pthread_create(&thread2, NULL, signaling_thread, NULL);
  32.  
  33. pthread_join(thread1, NULL);
  34. pthread_join(thread2, NULL);
  35.  
  36. pthread_mutex_destroy(&lock);
  37. pthread_cond_destroy(&condition);
  38. return 0;
  39. }
  40.  
Success #stdin #stdout 0s 5320KB
stdin
Standard input is empty
stdout
Waiting for signal...
Sending signal...
Received signal!