| 1 | /* Test for sem_post race: bug 14532. |
| 2 | Copyright (C) 2012-2024 Free Software Foundation, Inc. |
| 3 | This file is part of the GNU C Library. |
| 4 | |
| 5 | The GNU C Library is free software; you can redistribute it and/or |
| 6 | modify it under the terms of the GNU Lesser General Public |
| 7 | License as published by the Free Software Foundation; either |
| 8 | version 2.1 of the License, or (at your option) any later version. |
| 9 | |
| 10 | The GNU C Library is distributed in the hope that it will be useful, |
| 11 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 13 | Lesser General Public License for more details. |
| 14 | |
| 15 | You should have received a copy of the GNU Lesser General Public |
| 16 | License along with the GNU C Library; if not, see |
| 17 | <https://www.gnu.org/licenses/>. */ |
| 18 | |
| 19 | #include <pthread.h> |
| 20 | #include <semaphore.h> |
| 21 | #include <stdio.h> |
| 22 | |
| 23 | #define NTHREADS 10 |
| 24 | #define NITER 100000 |
| 25 | |
| 26 | sem_t sem; |
| 27 | int c; |
| 28 | volatile int thread_fail; |
| 29 | |
| 30 | static void * |
| 31 | tf (void *arg) |
| 32 | { |
| 33 | for (int i = 0; i < NITER; i++) |
| 34 | { |
| 35 | if (sem_wait (sem: &sem) != 0) |
| 36 | { |
| 37 | perror ("sem_wait" ); |
| 38 | thread_fail = 1; |
| 39 | } |
| 40 | ++c; |
| 41 | if (sem_post (sem: &sem) != 0) |
| 42 | { |
| 43 | perror ("sem_post" ); |
| 44 | thread_fail = 1; |
| 45 | } |
| 46 | } |
| 47 | return NULL; |
| 48 | } |
| 49 | |
| 50 | static int |
| 51 | do_test (void) |
| 52 | { |
| 53 | if (sem_init (sem: &sem, pshared: 0, value: 0) != 0) |
| 54 | { |
| 55 | perror ("sem_init" ); |
| 56 | return 1; |
| 57 | } |
| 58 | |
| 59 | pthread_t th[NTHREADS]; |
| 60 | for (int i = 0; i < NTHREADS; i++) |
| 61 | { |
| 62 | if (pthread_create (newthread: &th[i], NULL, start_routine: tf, NULL) != 0) |
| 63 | { |
| 64 | puts (s: "pthread_create failed" ); |
| 65 | return 1; |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | if (sem_post (sem: &sem) != 0) |
| 70 | { |
| 71 | perror ("sem_post" ); |
| 72 | return 1; |
| 73 | } |
| 74 | |
| 75 | for (int i = 0; i < NTHREADS; i++) |
| 76 | if (pthread_join (th: th[i], NULL) != 0) |
| 77 | { |
| 78 | puts (s: "pthread_join failed" ); |
| 79 | return 1; |
| 80 | } |
| 81 | |
| 82 | if (c != NTHREADS * NITER) |
| 83 | { |
| 84 | printf (format: "c = %d, should be %d\n" , c, NTHREADS * NITER); |
| 85 | return 1; |
| 86 | } |
| 87 | return thread_fail; |
| 88 | } |
| 89 | |
| 90 | #define TEST_FUNCTION do_test () |
| 91 | #include "../test-skeleton.c" |
| 92 | |