tst-mtx-basic.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /* C11 threads basic mutex tests.
  2. Copyright (C) 2018-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 <threads.h>
  16. #include <stdio.h>
  17. #include <unistd.h>
  18. #include <support/check.h>
  19. /* Shared mutex between child and parent. */
  20. static mtx_t mutex;
  21. /* Shared counter to check possible race conditions. */
  22. static int counter;
  23. static int
  24. child_add (void *arg)
  25. {
  26. if (mtx_lock (&mutex) != thrd_success)
  27. FAIL_EXIT1 ("mtx_lock failed");
  28. counter++;
  29. if (mtx_unlock (&mutex) != thrd_success)
  30. FAIL_EXIT1 ("mtx_unlock failed");
  31. thrd_exit (thrd_success);
  32. }
  33. static int
  34. do_test (void)
  35. {
  36. mtx_init (&mutex, mtx_plain);
  37. thrd_t id;
  38. if (thrd_create (&id, child_add, NULL) != thrd_success)
  39. FAIL_EXIT1 ("thrd_create failed");
  40. if (mtx_lock (&mutex) != thrd_success)
  41. FAIL_EXIT1 ("mtx_lock failed");
  42. counter++;
  43. if (mtx_unlock (&mutex) != thrd_success)
  44. FAIL_EXIT1 ("mtx_unlock failed");
  45. if (thrd_join (id, NULL) != thrd_success)
  46. FAIL_EXIT1 ("thrd_join failed");
  47. if (counter != 2)
  48. FAIL_EXIT1 ("counter (%d) != 2", counter);
  49. mtx_destroy (&mutex);
  50. return 0;
  51. }
  52. #include <support/test-driver.c>