pthread-cond-timedwait-example.cpp 1.8 KB

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