All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
as_cpu.h
Go to the documentation of this file.
1 /*
2  * Copyright 2008-2018 Aerospike, Inc.
3  *
4  * Portions may be licensed to Aerospike, Inc. under one or more contributor
5  * license agreements.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License"); you may not
8  * use this file except in compliance with the License. You may obtain a copy of
9  * the License at http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13  * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14  * License for the specific language governing permissions and limitations under
15  * the License.
16  */
17 #pragma once
18 
19 #include <pthread.h>
20 
21 #if defined(__APPLE__)
22 #include <mach/thread_policy.h>
23 #endif
24 
25 #if defined(__FreeBSD__)
26 #include <sys/_cpuset.h>
27 #include <sys/cpuset.h>
28 #include <pthread_np.h>
29 #endif
30 
31 #ifdef __cplusplus
32 extern "C" {
33 #endif
34 
35 /******************************************************************************
36  * FUNCTIONS
37  *****************************************************************************/
38 
39 /**
40  * Assign a thread attribute to a specific cpu core.
41  */
42 static inline int
43 as_cpu_assign_thread_attr(pthread_attr_t* attr, int cpu_id)
44 {
45 #if defined(__APPLE__) || defined(AS_ALPINE)
46  // CPU affinity will be set later.
47  return 0;
48 #elif defined(__FreeBSD__)
49  cpuset_t cpuset;
50  CPU_ZERO(&cpuset);
51  CPU_SET(cpu_id, &cpuset);
52  return pthread_attr_setaffinity_np(attr, sizeof(cpuset_t), &cpuset);
53 #else
54  cpu_set_t cpuset;
55  CPU_ZERO(&cpuset);
56  CPU_SET(cpu_id, &cpuset);
57  return pthread_attr_setaffinity_np(attr, sizeof(cpu_set_t), &cpuset);
58 #endif
59 }
60 
61 /**
62  * Assign a running thread to a specific cpu core.
63  */
64 static inline int
65 as_cpu_assign_thread(pthread_t thread, int cpu_id)
66 {
67 #if defined(__APPLE__)
68  thread_affinity_policy_data_t policy = {cpu_id};
69  thread_port_t mach_thread = pthread_mach_thread_np(thread);
70  return thread_policy_set(mach_thread, THREAD_AFFINITY_POLICY, (thread_policy_t)&policy, 1);
71 #elif defined(AS_ALPINE)
72  cpu_set_t cpuset;
73  CPU_ZERO(&cpuset);
74  CPU_SET(cpu_id, &cpuset);
75  return pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);
76 #else
77  // CPU affinity already set.
78  return 0;
79 #endif
80 }
81 
82 #ifdef __cplusplus
83 } // end extern "C"
84 #endif
static int as_cpu_assign_thread(pthread_t thread, int cpu_id)
Definition: as_cpu.h:65
static int as_cpu_assign_thread_attr(pthread_attr_t *attr, int cpu_id)
Definition: as_cpu.h:43