xref: /netbsd-src/external/lgpl3/mpfr/dist/examples/threads.c (revision ba125506a622fe649968631a56eba5d42ff57863)
1 /* Multithreading test to detect scaling issues with MPFR.
2 
3 Define:
4   * the function F;
5   * the precision PREC;
6   * the value V as an expression that will have the type double
7     (it may depend on the thread number i).
8 
9 Example:
10   gcc threads.c -lmpfr -lgmp -lpthread -DF=mpfr_sin -DPREC=200 -DV=100
11 
12 Copyright 2018-2023 Free Software Foundation, Inc.
13 Contributed by the AriC and Caramba projects, INRIA.
14 
15 This file is part of the GNU MPFR Library.
16 
17 The GNU MPFR Library is free software; you can redistribute it and/or modify
18 it under the terms of the GNU Lesser General Public License as published by
19 the Free Software Foundation; either version 3 of the License, or (at your
20 option) any later version.
21 
22 The GNU MPFR Library is distributed in the hope that it will be useful, but
23 WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
24 or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
25 License for more details.
26 
27 You should have received a copy of the GNU Lesser General Public License
28 along with the GNU MPFR Library; see the file COPYING.LESSER.  If not, see
29 https://www.gnu.org/licenses/ or write to the Free Software Foundation, Inc.,
30 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
31 */
32 
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <pthread.h>
36 
37 #include <mpfr.h>
38 
39 #define MAX_THREADS 256
40 
41 static int m;
42 
start_routine(void * arg)43 static void *start_routine (void *arg)
44 {
45   mpfr_t x, y;
46   int i = *(int *) arg, j;
47 
48   (void) i;  /* avoid a warning if i is not used by V */
49 
50   mpfr_inits2 (PREC, x, y, (mpfr_ptr) 0);
51   mpfr_set_d (x, (V), MPFR_RNDN);
52 
53   for (j = 0; j < m; j++)
54     F (y, x, MPFR_RNDN);
55 
56   mpfr_clears (x, y, (mpfr_ptr) 0);
57   pthread_exit (NULL);
58 }
59 
main(int argc,char * argv[])60 int main (int argc, char *argv[])
61 {
62   int i, n;
63   pthread_t tid[MAX_THREADS];
64 
65   if (argc != 3 ||
66       (m = atoi (argv[1]), m < 1) ||
67       (n = atoi (argv[2]), n < 1 || n > MAX_THREADS))
68     {
69       fprintf (stderr, "Usage: %s <#iterations> <#threads>\n", argv[0]);
70       exit (1);
71     }
72 
73   printf ("%d iteration(s), %d thread(s).\n", m, n);
74 
75   for (i = 0; i < n; i++)
76     if (pthread_create (&tid[i], NULL, start_routine, &i) != 0)
77       {
78         fprintf (stderr, "%s: failed to create thread %d\n", argv[0], i);
79         exit (1);
80       }
81 
82   for (i = 0; i < n; i++)
83     if (pthread_join (tid[i], NULL) != 0)
84       {
85         fprintf (stderr, "%s: failed to join thread %d\n", argv[0], i);
86         exit (1);
87       }
88 
89   return 0;
90 }
91