pthread-cond-timedwait-example.cpp 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <errno.h>
  5. #include <unistd.h>
  6. #include <ctime>
  7. #include <cstring>
  8. #include <cassert>
  9. struct worker_t
  10. {
  11. const char* name;
  12. int count;
  13. pthread_t thread;
  14. pthread_mutex_t lock;
  15. pthread_cond_t cond;
  16. long int wait_time;
  17. };
  18. void* run_worker(void* args)
  19. {
  20. struct timespec time_to_wait = {0, 0};
  21. worker_t* worker = (worker_t*)args;
  22. worker->count = 0;
  23. while (worker->count < 25) {
  24. time_to_wait.tv_sec = time(nullptr) + worker->wait_time;
  25. pthread_mutex_lock(&worker->lock);
  26. int rc = pthread_cond_timedwait(&worker->cond, &worker->lock, &time_to_wait);
  27. // Validate return code is always timed out.
  28. assert(rc == -1);
  29. assert(errno == ETIMEDOUT);
  30. worker->count++;
  31. printf("Increase worker[%s] count to [%d]\n", worker->name, worker->count);
  32. pthread_mutex_unlock(&worker->lock);
  33. }
  34. return nullptr;
  35. }
  36. void init_worker(worker_t* worker, const char* name, long int wait_time)
  37. {
  38. worker->name = name;
  39. worker->wait_time = wait_time;
  40. pthread_attr_t attr;
  41. pthread_attr_init(&attr);
  42. pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
  43. pthread_mutex_init(&worker->lock, nullptr);
  44. pthread_cond_init(&worker->cond, nullptr);
  45. pthread_create(&worker->thread, &attr, &run_worker, (void*) worker);
  46. pthread_attr_destroy(&attr);
  47. }
  48. int main()
  49. {
  50. worker_t worker_a;
  51. init_worker(&worker_a, "A", 2L);
  52. worker_t worker_b;
  53. init_worker(&worker_b, "B", 4L);
  54. pthread_join(worker_a.thread, nullptr);
  55. pthread_join(worker_b.thread, nullptr);
  56. return EXIT_SUCCESS;
  57. }