tst-cond16.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* Copyright (C) 2004 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Jakub Jelinek <jakub@redhat.com>, 2004.
  4. The GNU C Library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. The GNU C Library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with the GNU C Library; if not, see
  14. <http://www.gnu.org/licenses/>. */
  15. #include <errno.h>
  16. #include <pthread.h>
  17. #include <stdbool.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <unistd.h>
  21. pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
  22. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
  23. bool n, exiting;
  24. FILE *f;
  25. int count;
  26. void *
  27. tf (void *dummy)
  28. {
  29. bool loop = true;
  30. while (loop)
  31. {
  32. pthread_mutex_lock (&lock);
  33. while (n && !exiting)
  34. pthread_cond_wait (&cv, &lock);
  35. n = true;
  36. pthread_mutex_unlock (&lock);
  37. fputs (".", f);
  38. pthread_mutex_lock (&lock);
  39. n = false;
  40. if (exiting)
  41. loop = false;
  42. #ifdef UNLOCK_AFTER_BROADCAST
  43. pthread_cond_broadcast (&cv);
  44. pthread_mutex_unlock (&lock);
  45. #else
  46. pthread_mutex_unlock (&lock);
  47. pthread_cond_broadcast (&cv);
  48. #endif
  49. }
  50. return NULL;
  51. }
  52. int
  53. do_test (void)
  54. {
  55. f = fopen ("/dev/null", "w");
  56. if (f == NULL)
  57. {
  58. printf ("couldn't open /dev/null, %m\n");
  59. return 1;
  60. }
  61. count = sysconf (_SC_NPROCESSORS_ONLN);
  62. if (count <= 0)
  63. count = 1;
  64. count *= 4;
  65. pthread_t th[count];
  66. int i, ret;
  67. for (i = 0; i < count; ++i)
  68. if ((ret = pthread_create (&th[i], NULL, tf, NULL)) != 0)
  69. {
  70. errno = ret;
  71. printf ("pthread_create %d failed: %m\n", i);
  72. return 1;
  73. }
  74. struct timespec ts = { .tv_sec = 20, .tv_nsec = 0 };
  75. while (nanosleep (&ts, &ts) != 0);
  76. pthread_mutex_lock (&lock);
  77. exiting = true;
  78. pthread_mutex_unlock (&lock);
  79. for (i = 0; i < count; ++i)
  80. pthread_join (th[i], NULL);
  81. fclose (f);
  82. return 0;
  83. }
  84. #define TEST_FUNCTION do_test ()
  85. #define TIMEOUT 40
  86. #include "../test-skeleton.c"