1 /* Copyright (C) 2002-2021 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@redhat.com>, 2002.
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.
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.
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/>. */
33 #include <sys/param.h>
34 #include <sys/types.h>
37 # define MAX_THREADS 100000
39 #ifndef DEFAULT_THREADS
40 # define DEFAULT_THREADS 50
44 #define OPT_TO_THREAD 300
45 #define OPT_TO_PROCESS 301
46 #define OPT_SYNC_SIGNAL 302
47 #define OPT_SYNC_JOIN 303
48 #define OPT_TOPLEVEL 304
51 static const struct argp_option options
[] =
53 { NULL
, 0, NULL
, 0, "\
54 This is a test for threads so we allow ther user to selection the number of \
55 threads which are used at any one time. Independently the total number of \
56 rounds can be selected. This is the total number of threads which will have \
57 run when the process terminates:" },
58 { "threads", 't', "NUMBER", 0, "Number of threads used at once" },
59 { "starts", 's', "NUMBER", 0, "Total number of working threads" },
60 { "toplevel", OPT_TOPLEVEL
, "NUMBER", 0,
61 "Number of toplevel threads which start the other threads; this \
62 implies --sync-join" },
64 { NULL
, 0, NULL
, 0, "\
65 Each thread can do one of two things: sleep or do work. The latter is 100% \
66 CPU bound. The work load is the probability a thread does work. All values \
67 from zero to 100 (inclusive) are valid. How often each thread repeats this \
68 can be determined by the number of rounds. The work cost determines how long \
69 each work session (not sleeping) takes. If it is zero a thread would \
70 effectively nothing. By setting the number of rounds to zero the thread \
71 does no work at all and pure thread creation times can be measured." },
72 { "workload", 'w', "PERCENT", 0, "Percentage of time spent working" },
73 { "workcost", 'c', "NUMBER", 0,
74 "Factor in the cost of each round of working" },
75 { "rounds", 'r', "NUMBER", 0, "Number of rounds each thread runs" },
77 { NULL
, 0, NULL
, 0, "\
78 There are a number of different methods how thread creation can be \
79 synchronized. Synchronization is necessary since the number of concurrently \
80 running threads is limited." },
81 { "sync-signal", OPT_SYNC_SIGNAL
, NULL
, 0,
82 "Synchronize using a signal (default)" },
83 { "sync-join", OPT_SYNC_JOIN
, NULL
, 0, "Synchronize using pthread_join" },
85 { NULL
, 0, NULL
, 0, "\
86 One parameter for each threads execution is the size of the stack. If this \
87 parameter is not used the system's default stack size is used. If many \
88 threads are used the stack size should be chosen quite small." },
89 { "stacksize", 'S', "BYTES", 0, "Size of threads stack" },
90 { "guardsize", 'g', "BYTES", 0,
91 "Size of stack guard area; must fit into the stack" },
93 { NULL
, 0, NULL
, 0, "Signal options:" },
94 { "to-thread", OPT_TO_THREAD
, NULL
, 0, "Send signal to main thread" },
95 { "to-process", OPT_TO_PROCESS
, NULL
, 0,
96 "Send signal to process (default)" },
98 { NULL
, 0, NULL
, 0, "Administrative options:" },
99 { "progress", 'p', NULL
, 0, "Show signs of progress" },
100 { "timing", 'T', NULL
, 0,
101 "Measure time from startup to the last thread finishing" },
102 { NULL
, 0, NULL
, 0, NULL
}
105 /* Prototype for option handler. */
106 static error_t
parse_opt (int key
, char *arg
, struct argp_state
*state
);
108 /* Data structure to communicate with argp functions. */
109 static struct argp argp
=
115 static unsigned long int threads
= DEFAULT_THREADS
;
116 static unsigned long int workload
= 75;
117 static unsigned long int workcost
= 20;
118 static unsigned long int rounds
= 10;
119 static long int starts
= 5000;
120 static unsigned long int stacksize
;
121 static long int guardsize
= -1;
122 static bool progress
;
124 static bool to_thread
;
125 static unsigned long int toplevel
= 1;
128 static long int running
;
129 static pthread_mutex_t running_mutex
= PTHREAD_MUTEX_INITIALIZER
;
132 static pthread_t tmain
;
135 static struct timespec start_time
;
138 static pthread_mutex_t sum_mutex
= PTHREAD_MUTEX_INITIALIZER
;
149 /* We use 64bit values for the times. */
150 typedef unsigned long long int hp_timing_t
;
153 /* Attributes for all created threads. */
154 static pthread_attr_t attr
;
161 unsigned int state
= (unsigned long int) arg
;
163 for (i
= 0; i
< rounds
; ++i
)
165 /* Determine what to do. */
168 /* Uniform distribution. */
170 rnum
= rand_r (&state
);
171 while (rnum
>= UINT_MAX
- (UINT_MAX
% 100));
178 int a
[4] = { i
, rnum
, i
+ rnum
, rnum
- i
};
181 write (STDERR_FILENO
, "c", 1);
183 for (j
= 0; j
< workcost
; ++j
)
187 a
[2] += a
[1] ^ 0x3423423;
191 pthread_mutex_lock (&sum_mutex
);
192 sum
+= a
[0] + a
[1] + a
[2] + a
[3];
193 pthread_mutex_unlock (&sum_mutex
);
201 tv
.tv_nsec
= 10000000;
204 write (STDERR_FILENO
, "w", 1);
206 nanosleep (&tv
, NULL
);
215 thread_function (void *arg
)
219 pthread_mutex_lock (&running_mutex
);
220 if (--running
<= 0 && starts
<= 0)
224 write (STDERR_FILENO
, "\n", 1);
228 struct timespec end_time
;
230 if (clock_gettime (cl
, &end_time
) == 0)
232 end_time
.tv_sec
-= start_time
.tv_sec
;
233 end_time
.tv_nsec
-= start_time
.tv_nsec
;
234 if (end_time
.tv_nsec
< 0)
236 end_time
.tv_nsec
+= 1000000000;
240 printf ("\nRuntime: %lu.%09lu seconds\n",
241 (unsigned long int) end_time
.tv_sec
,
242 (unsigned long int) end_time
.tv_nsec
);
246 printf ("Result: %08x\n", sum
);
250 pthread_mutex_unlock (&running_mutex
);
252 if (sync_method
== sync_signal
)
255 /* This code sends a signal to the main thread. */
256 pthread_kill (tmain
, SIGUSR1
);
258 /* Use this code to test sending a signal to the process. */
263 write (STDERR_FILENO
, "f", 1);
272 unsigned int threads
;
277 start_threads (void *arg
)
279 struct start_info
*si
= arg
;
280 unsigned int starts
= si
->starts
;
281 pthread_t ths
[si
->threads
];
282 unsigned int state
= starts
;
288 write (STDERR_FILENO
, "T", 1);
290 memset (ths
, '\0', sizeof (pthread_t
) * si
->threads
);
296 /* Wait for the threads in the order they were created. */
297 err
= pthread_join (ths
[i
], NULL
);
299 error (EXIT_FAILURE
, err
, "cannot join thread");
302 write (STDERR_FILENO
, "f", 1);
305 err
= pthread_create (&ths
[i
], &attr
, work
,
306 (void *) (long) (rand_r (&state
) + starts
+ i
));
309 error (EXIT_FAILURE
, err
, "cannot start thread");
312 write (STDERR_FILENO
, "t", 1);
314 if (++i
== si
->threads
)
323 err
= pthread_join (ths
[i
], NULL
);
325 error (EXIT_FAILURE
, err
, "cannot join thread");
328 write (STDERR_FILENO
, "f", 1);
331 if (++i
== si
->threads
)
337 write (STDERR_FILENO
, "F", 1);
344 main (int argc
, char *argv
[])
349 pthread_t
*ths
= NULL
;
354 /* Parse and process arguments. */
355 argp_parse (&argp
, argc
, argv
, 0, &remaining
, NULL
);
357 if (sync_method
== sync_join
)
359 ths
= (pthread_t
*) calloc (threads
, sizeof (pthread_t
));
361 error (EXIT_FAILURE
, errno
,
362 "cannot allocate memory for thread descriptor array");
372 if (toplevel
> threads
)
374 printf ("resetting number of toplevel threads to %lu to not surpass number to concurrent threads\n",
381 if (clock_getcpuclockid (0, &cl
) != 0
382 || clock_gettime (cl
, &start_time
) != 0)
386 /* We need this later. */
388 tmain
= pthread_self ();
390 /* We use signal SIGUSR1 for communication between the threads and
391 the main thread. We only want sychronous notification. */
392 if (sync_method
== sync_signal
)
395 sigaddset (&ss
, SIGUSR1
);
396 if (sigprocmask (SIG_BLOCK
, &ss
, NULL
) != 0)
397 error (EXIT_FAILURE
, errno
, "cannot set signal mask");
400 /* Create the thread attributes. */
401 pthread_attr_init (&attr
);
403 /* If the user provided a stack size use it. */
405 && pthread_attr_setstacksize (&attr
, stacksize
) != 0)
406 puts ("could not set stack size; will use default");
407 /* And stack guard size. */
409 && pthread_attr_setguardsize (&attr
, guardsize
) != 0)
410 puts ("invalid stack guard size; will use default");
412 /* All threads are created detached if we are not using pthread_join
414 if (sync_method
!= sync_join
)
415 pthread_attr_setdetachstate (&attr
, PTHREAD_CREATE_DETACHED
);
417 if (sync_method
== sync_signal
)
422 bool do_wait
= false;
424 pthread_mutex_lock (&running_mutex
);
428 do_wait
= ++running
>= threads
&& starts
> 0;
430 pthread_mutex_unlock (&running_mutex
);
436 write (STDERR_FILENO
, "t", 1);
438 err
= pthread_create (&ths
[empty
], &attr
, thread_function
,
441 error (EXIT_FAILURE
, err
, "cannot start thread %lu", starts
);
447 sigwaitinfo (&ss
, NULL
);
450 /* Do nothing anymore. On of the threads will terminate the program. */
452 sigdelset (&ss
, SIGINT
);
458 pthread_t ths
[toplevel
];
459 struct start_info si
[toplevel
];
462 for (i
= 0; i
< toplevel
; ++i
)
464 unsigned int child_starts
= starts
/ (toplevel
- i
);
465 unsigned int child_threads
= threads
/ (toplevel
- i
);
468 si
[i
].starts
= child_starts
;
469 si
[i
].threads
= child_threads
;
471 err
= pthread_create (&ths
[i
], &attr
, start_threads
, &si
[i
]);
473 error (EXIT_FAILURE
, err
, "cannot start thread");
475 starts
-= child_starts
;
476 threads
-= child_threads
;
479 for (i
= 0; i
< toplevel
; ++i
)
481 int err
= pthread_join (ths
[i
], NULL
);
484 error (EXIT_FAILURE
, err
, "cannot join thread");
489 write (STDERR_FILENO
, "\n", 1);
493 struct timespec end_time
;
495 if (clock_gettime (cl
, &end_time
) == 0)
497 end_time
.tv_sec
-= start_time
.tv_sec
;
498 end_time
.tv_nsec
-= start_time
.tv_nsec
;
499 if (end_time
.tv_nsec
< 0)
501 end_time
.tv_nsec
+= 1000000000;
505 printf ("\nRuntime: %lu.%09lu seconds\n",
506 (unsigned long int) end_time
.tv_sec
,
507 (unsigned long int) end_time
.tv_nsec
);
511 printf ("Result: %08x\n", sum
);
521 /* Handle program arguments. */
523 parse_opt (int key
, char *arg
, struct argp_state
*state
)
525 unsigned long int num
;
531 num
= strtoul (arg
, NULL
, 0);
532 if (num
<= MAX_THREADS
)
536 number of threads limited to %u; recompile with a higher limit if necessary",
541 num
= strtoul (arg
, NULL
, 0);
545 puts ("workload must be between 0 and 100 percent");
549 workcost
= strtoul (arg
, NULL
, 0);
553 rounds
= strtoul (arg
, NULL
, 0);
557 starts
= strtoul (arg
, NULL
, 0);
561 num
= strtoul (arg
, NULL
, 0);
562 if (num
>= PTHREAD_STACK_MIN
)
565 printf ("minimum stack size is %d\n", PTHREAD_STACK_MIN
);
569 snum
= strtol (arg
, NULL
, 0);
571 printf ("invalid guard size %s\n", arg
);
592 case OPT_SYNC_SIGNAL
:
593 sync_method
= sync_signal
;
597 sync_method
= sync_join
;
601 num
= strtoul (arg
, NULL
, 0);
602 if (num
< MAX_THREADS
)
606 number of threads limited to %u; recompile with a higher limit if necessary",
608 sync_method
= sync_join
;
612 return ARGP_ERR_UNKNOWN
;
622 /* We read the information from the /proc filesystem. It contains at
627 We search for this line and convert the number in an integer. */
628 static hp_timing_t result
;
631 /* If this function was called before, we know the result. */
635 fd
= open ("/proc/cpuinfo", O_RDONLY
);
636 if (__glibc_likely (fd
!= -1))
638 /* XXX AFAIK the /proc filesystem can generate "files" only up
639 to a size of 4096 bytes. */
643 n
= read (fd
, buf
, sizeof buf
);
644 if (__builtin_expect (n
, 1) > 0)
646 char *mhz
= memmem (buf
, n
, "cpu MHz", 7);
648 if (__glibc_likely (mhz
!= NULL
))
650 char *endp
= buf
+ n
;
651 int seen_decpoint
= 0;
654 /* Search for the beginning of the string. */
655 while (mhz
< endp
&& (*mhz
< '0' || *mhz
> '9') && *mhz
!= '\n')
658 while (mhz
< endp
&& *mhz
!= '\n')
660 if (*mhz
>= '0' && *mhz
<= '9')
663 result
+= *mhz
- '0';
667 else if (*mhz
== '.')
673 /* Compensate for missing digits at the end. */
674 while (ndigits
++ < 6)
687 clock_getcpuclockid (pid_t pid
, clockid_t
*clock_id
)
689 /* We don't allow any process ID but our own. */
690 if (pid
!= 0 && pid
!= getpid ())
693 #ifdef CLOCK_PROCESS_CPUTIME_ID
694 /* Store the number. */
695 *clock_id
= CLOCK_PROCESS_CPUTIME_ID
;
699 /* We don't have a timer for that. */
706 #define HP_TIMING_NOW(Var) __asm__ __volatile__ ("rdtsc" : "=A" (Var))
707 #elif defined __x86_64__
708 # define HP_TIMING_NOW(Var) \
709 ({ unsigned int _hi, _lo; \
710 asm volatile ("rdtsc" : "=a" (_lo), "=d" (_hi)); \
711 (Var) = ((unsigned long long int) _hi << 32) | _lo; })
712 #elif defined __ia64__
713 #define HP_TIMING_NOW(Var) __asm__ __volatile__ ("mov %0=ar.itc" : "=r" (Var) : : "memory")
715 #error "HP_TIMING_NOW missing"
718 /* Get current value of CLOCK and store it in TP. */
720 clock_gettime (clockid_t clock_id
, struct timespec
*tp
)
726 case CLOCK_PROCESS_CPUTIME_ID
:
729 static hp_timing_t freq
;
732 /* Get the current counter. */
737 freq
= get_clockfreq ();
742 /* Compute the seconds. */
743 tp
->tv_sec
= tsc
/ freq
;
745 /* And the nanoseconds. This computation should be stable until
746 we get machines with about 16GHz frequency. */
747 tp
->tv_nsec
= ((tsc
% freq
) * UINT64_C (1000000000)) / freq
;