tst-too-many-cleanups.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. pthread_cleanup_pop(0);
  48. }
  49. static void thread_killed(void *arg)
  50. {
  51. static num_times_called = 0;
  52. warnf("killing %p [cnt=%i]\n", arg, ++num_times_called);
  53. assert(num_times_called == 1);
  54. /* pick any cancellation endpoint, sleep() will do just fine */
  55. while (1) {
  56. warnf("sleeping in cancellation endpoint ...\n");
  57. sleep(1);
  58. }
  59. warnf("done cleaning up\n");
  60. }
  61. int main(int argc, char *argv[])
  62. {
  63. int count = 3;
  64. pthread_t app_pthread_id;
  65. ok_to_kill_thread = 0;
  66. pthread_create(&app_pthread_id, NULL, KillMeThread, NULL);
  67. warnf("waiting for thread to prepare itself\n");
  68. while (!ok_to_kill_thread)
  69. ;
  70. while (count--) {
  71. warnf("killing thread\n");
  72. pthread_cancel(app_pthread_id);
  73. sleep(3);
  74. }
  75. return 0;
  76. }