tst-too-many-cleanups.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * This illustrates the bug where the cleanup function
  3. * of a thread may be called too many times.
  4. *
  5. * main thread:
  6. * - grab mutex
  7. * - spawn thread1
  8. * - go to sleep
  9. * thread1:
  10. * - register cleanup handler via pthread_cleanup_push()
  11. * - try to grab mutex and sleep
  12. * main:
  13. * - kill thread1
  14. * - go to sleep
  15. * thread1 cleanup handler:
  16. * - try to grab mutex and sleep
  17. * main:
  18. * - kill thread1
  19. * - go to sleep
  20. * thread1 cleanup handler:
  21. * - wrongly called again
  22. */
  23. #ifndef _GNU_SOURCE
  24. #define _GNU_SOURCE
  25. #endif
  26. #include <stdio.h>
  27. #include <stdlib.h>
  28. #include <pthread.h>
  29. #include <assert.h>
  30. #include <unistd.h>
  31. #define warn(fmt, args...) fprintf(stderr, "[%p] " fmt, (void*)pthread_self(), ## args)
  32. #define warnf(fmt, args...) warn("%s:%i: " fmt, __FUNCTION__, __LINE__, ## args)
  33. int ok_to_kill_thread;
  34. static void thread_killed(void *arg);
  35. static void *KillMeThread(void *thread_par)
  36. {
  37. pthread_t pthread_id;
  38. warnf("Starting child thread\n");
  39. pthread_id = pthread_self();
  40. pthread_cleanup_push(thread_killed, (void *)pthread_id);
  41. pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);
  42. pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
  43. /* main code */
  44. warnf("please kill me now\n");
  45. while (1) {
  46. ok_to_kill_thread = 1;
  47. sleep(1);
  48. }
  49. pthread_cleanup_pop(0);
  50. return 0;
  51. }
  52. static void thread_killed(void *arg)
  53. {
  54. static int num_times_called = 0;
  55. warnf("killing %p [cnt=%i]\n", arg, ++num_times_called);
  56. assert(num_times_called == 1);
  57. /* pick any cancellation endpoint, sleep() will do just fine */
  58. while (1) {
  59. warnf("sleeping in cancellation endpoint ...\n");
  60. sleep(1);
  61. }
  62. warnf("done cleaning up\n");
  63. }
  64. int main(int argc, char *argv[])
  65. {
  66. int count = 3;
  67. pthread_t app_pthread_id;
  68. /* need to tweak this test a bit to play nice with signals and LT */
  69. return 0;
  70. ok_to_kill_thread = 0;
  71. pthread_create(&app_pthread_id, NULL, KillMeThread, NULL);
  72. warnf("waiting for thread to prepare itself\n");
  73. while (!ok_to_kill_thread)
  74. sleep(1);
  75. while (count--) {
  76. warnf("killing thread\n");
  77. pthread_cancel(app_pthread_id);
  78. sleep(3);
  79. }
  80. return 0;
  81. }