tst-sem14.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Test for sem_post race: bug 14532.
  2. Copyright (C) 2012-2019 Free Software Foundation, Inc.
  3. This file is part of the GNU C Library.
  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 <pthread.h>
  16. #include <semaphore.h>
  17. #include <stdio.h>
  18. #define NTHREADS 10
  19. #define NITER 100000
  20. sem_t sem;
  21. int c;
  22. volatile int thread_fail;
  23. static void *
  24. tf (void *arg)
  25. {
  26. for (int i = 0; i < NITER; i++)
  27. {
  28. if (sem_wait (&sem) != 0)
  29. {
  30. perror ("sem_wait");
  31. thread_fail = 1;
  32. }
  33. ++c;
  34. if (sem_post (&sem) != 0)
  35. {
  36. perror ("sem_post");
  37. thread_fail = 1;
  38. }
  39. }
  40. return NULL;
  41. }
  42. static int
  43. do_test (void)
  44. {
  45. if (sem_init (&sem, 0, 0) != 0)
  46. {
  47. perror ("sem_init");
  48. return 1;
  49. }
  50. pthread_t th[NTHREADS];
  51. for (int i = 0; i < NTHREADS; i++)
  52. {
  53. if (pthread_create (&th[i], NULL, tf, NULL) != 0)
  54. {
  55. puts ("pthread_create failed");
  56. return 1;
  57. }
  58. }
  59. if (sem_post (&sem) != 0)
  60. {
  61. perror ("sem_post");
  62. return 1;
  63. }
  64. for (int i = 0; i < NTHREADS; i++)
  65. if (pthread_join (th[i], NULL) != 0)
  66. {
  67. puts ("pthread_join failed");
  68. return 1;
  69. }
  70. if (c != NTHREADS * NITER)
  71. {
  72. printf ("c = %d, should be %d\n", c, NTHREADS * NITER);
  73. return 1;
  74. }
  75. return thread_fail;
  76. }
  77. #define TEST_FUNCTION do_test ()
  78. #include "../test-skeleton.c"