1 /* Separate thread test for pthread_getaffinity_np, pthread_setaffinity_np.
2 Copyright (C) 2015-2022 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
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.
9
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.
14
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/>. */
18
19 #include <errno.h>
20 #include <pthread.h>
21 #include <stdbool.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24
25 /* Defined for the benefit of tst-skeleton-thread-affinity.c, included
26 below. This variant runs the functions on a separate thread. */
27
28 struct affinity_access_task
29 {
30 pthread_t thread;
31 cpu_set_t *set;
32 size_t size;
33 bool get;
34 int result;
35 };
36
37 static void *
affinity_access_thread(void * closure)38 affinity_access_thread (void *closure)
39 {
40 struct affinity_access_task *task = closure;
41 if (task->get)
42 task->result = pthread_getaffinity_np
43 (task->thread, task->size, task->set);
44 else
45 task->result = pthread_setaffinity_np
46 (task->thread, task->size, task->set);
47 return NULL;
48 }
49
50 static int
run_affinity_access_thread(cpu_set_t * set,size_t size,bool get)51 run_affinity_access_thread (cpu_set_t *set, size_t size, bool get)
52 {
53 struct affinity_access_task task =
54 {
55 .thread = pthread_self (),
56 .set = set,
57 .size = size,
58 .get = get
59 };
60 pthread_t thr;
61 int ret = pthread_create (&thr, NULL, affinity_access_thread, &task);
62 if (ret != 0)
63 {
64 errno = ret;
65 printf ("error: could not create affinity access thread: %m\n");
66 abort ();
67 }
68 ret = pthread_join (thr, NULL);
69 if (ret != 0)
70 {
71 errno = ret;
72 printf ("error: could not join affinity access thread: %m\n");
73 abort ();
74 }
75 if (task.result != 0)
76 {
77 errno = task.result;
78 return -1;
79 }
80 return 0;
81 }
82
83 static int
setaffinity(size_t size,const cpu_set_t * set)84 setaffinity (size_t size, const cpu_set_t *set)
85 {
86 return run_affinity_access_thread ((cpu_set_t *) set, size, false);
87 }
88
89 static int
getaffinity(size_t size,cpu_set_t * set)90 getaffinity (size_t size, cpu_set_t *set)
91 {
92 return run_affinity_access_thread (set, size, true);
93 }
94
95 #include "tst-skeleton-thread-affinity.c"
96