tst-once2.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. /* Copyright (C) 2002, 2004 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
  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 <stdio.h>
  17. #include <stdlib.h>
  18. #include <time.h>
  19. #define N 100
  20. static pthread_once_t once = PTHREAD_ONCE_INIT;
  21. static int global;
  22. static void
  23. once_handler (void)
  24. {
  25. struct timespec ts;
  26. ++global;
  27. ts.tv_sec = 2;
  28. ts.tv_nsec = 0;
  29. nanosleep (&ts, NULL);
  30. }
  31. static void *
  32. tf (void *arg)
  33. {
  34. pthread_once (&once, once_handler);
  35. if (global != 1)
  36. {
  37. printf ("thread %ld: global == %d\n", (long int) arg, global);
  38. exit (1);
  39. }
  40. return NULL;
  41. }
  42. static int
  43. do_test (void)
  44. {
  45. pthread_attr_t at;
  46. pthread_t th[N];
  47. int cnt;
  48. if (pthread_attr_init (&at) != 0)
  49. {
  50. puts ("attr_init failed");
  51. return 1;
  52. }
  53. if (pthread_attr_setstacksize (&at, 1 * 1024 * 1024) != 0)
  54. {
  55. puts ("attr_setstacksize failed");
  56. return 1;
  57. }
  58. for (cnt = 0; cnt < N; ++cnt)
  59. if (pthread_create (&th[cnt], &at, tf, (void *) (long int) cnt) != 0)
  60. {
  61. printf ("creation of thread %d failed\n", cnt);
  62. return 1;
  63. }
  64. if (pthread_attr_destroy (&at) != 0)
  65. {
  66. puts ("attr_destroy failed");
  67. return 1;
  68. }
  69. for (cnt = 0; cnt < N; ++cnt)
  70. if (pthread_join (th[cnt], NULL) != 0)
  71. {
  72. printf ("join of thread %d failed\n", cnt);
  73. return 1;
  74. }
  75. return 0;
  76. }
  77. #define TEST_FUNCTION do_test ()
  78. #define TIMEOUT 4
  79. #include "../test-skeleton.c"