Back to index

glibc  2.9
tst-once2.c
Go to the documentation of this file.
00001 /* Copyright (C) 2002, 2004 Free Software Foundation, Inc.
00002    This file is part of the GNU C Library.
00003    Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
00004 
00005    The GNU C Library is free software; you can redistribute it and/or
00006    modify it under the terms of the GNU Lesser General Public
00007    License as published by the Free Software Foundation; either
00008    version 2.1 of the License, or (at your option) any later version.
00009 
00010    The GNU C Library is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00013    Lesser General Public License for more details.
00014 
00015    You should have received a copy of the GNU Lesser General Public
00016    License along with the GNU C Library; if not, write to the Free
00017    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
00018    02111-1307 USA.  */
00019 
00020 #include <pthread.h>
00021 #include <stdio.h>
00022 #include <stdlib.h>
00023 #include <time.h>
00024 
00025 
00026 #define N 100
00027 
00028 static pthread_once_t once = PTHREAD_ONCE_INIT;
00029 
00030 static int global;
00031 
00032 static void
00033 once_handler (void)
00034 {
00035   struct timespec ts;
00036 
00037   ++global;
00038 
00039   ts.tv_sec = 2;
00040   ts.tv_nsec = 0;
00041   nanosleep (&ts, NULL);
00042 }
00043 
00044 
00045 static void *
00046 tf (void *arg)
00047 {
00048   pthread_once (&once, once_handler);
00049 
00050   if (global != 1)
00051     {
00052       printf ("thread %ld: global == %d\n", (long int) arg, global);
00053       exit (1);
00054     }
00055 
00056   return NULL;
00057 }
00058 
00059 
00060 static int
00061 do_test (void)
00062 {
00063   pthread_attr_t at;
00064   pthread_t th[N];
00065   int cnt;
00066 
00067   if (pthread_attr_init (&at) != 0)
00068     {
00069       puts ("attr_init failed");
00070       return 1;
00071     }
00072 
00073   if (pthread_attr_setstacksize (&at, 1 * 1024 * 1024) != 0)
00074     {
00075       puts ("attr_setstacksize failed");
00076       return 1;
00077     }
00078 
00079   for (cnt = 0; cnt < N; ++cnt)
00080     if (pthread_create (&th[cnt], &at, tf, (void *) (long int) cnt) != 0)
00081       {
00082        printf ("creation of thread %d failed\n", cnt);
00083        return 1;
00084       }
00085 
00086   if (pthread_attr_destroy (&at) != 0)
00087     {
00088       puts ("attr_destroy failed");
00089       return 1;
00090     }
00091 
00092   for (cnt = 0; cnt < N; ++cnt)
00093     if (pthread_join (th[cnt], NULL) != 0)
00094       {
00095        printf ("join of thread %d failed\n", cnt);
00096        return 1;
00097       }
00098 
00099   return 0;
00100 }
00101 
00102 #define TEST_FUNCTION do_test ()
00103 #define TIMEOUT 4
00104 #include "../test-skeleton.c"