1 //  cross-platform wrapper for setting thread affinity
2 //  Copyright (C) 2009 Tim Blechmann
3 //
4 //  This program is free software; you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation; either version 2 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program; see the file COPYING.  If not, write to
16 //  the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor,
17 //  Boston, MA 02110-1301, USA.
18 
19 /** \file thread_affinity.hpp */
20 
21 #ifndef NOVA_TT_THREAD_AFFINITY_HPP
22 #define NOVA_TT_THREAD_AFFINITY_HPP
23 
24 #ifdef __linux__
25 
26 #ifndef _GNU_SOURCE
27 #define _GNU_SOURCE
28 #endif
29 #include <pthread.h>
30 
31 namespace nova {
32 
33 /** set the affinity of a thread
34  *
35  *  \return true, if successful, false otherwise
36  */
thread_set_affinity(int i)37 inline bool thread_set_affinity(int i)
38 {
39     pthread_t thread = pthread_self();
40 
41     cpu_set_t cpuset;
42     CPU_ZERO(&cpuset);
43     int status = CPU_SET(i, &cpuset);
44     int error = pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
45 
46     return error == 0;
47 }
48 
49 }
50 
51 #elif __APPLE__
52 
53 #include <pthread.h>
54 
55 #include <mach/thread_policy.h>
56 #include <mach/thread_act.h>
57 
58 namespace nova {
59 
thread_set_affinity(int i)60 inline bool thread_set_affinity(int i)
61 {
62     thread_affinity_policy affinityPolicy { i + 1 };
63     kern_return_t status = thread_policy_set( pthread_mach_thread_np(pthread_self()),
64                                               THREAD_AFFINITY_POLICY,
65                                               (thread_policy_t)&affinityPolicy,
66                                               THREAD_AFFINITY_POLICY_COUNT
67                                             );
68 
69     return status == KERN_SUCCESS;
70 }
71 
72 }
73 
74 #else
75 
76 namespace nova {
77 
thread_set_affinity(int i)78 inline bool thread_set_affinity(int i)
79 {
80     return false;
81 }
82 
83 }
84 
85 #endif
86 
87 #endif /* NOVA_TT_THREAD_AFFINITY_HPP */
88