-
Notifications
You must be signed in to change notification settings - Fork 227
/
affinity.patch
100 lines (95 loc) · 2.48 KB
/
affinity.patch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
--- ThreadPool.h Wed May 17 15:01:04 2017
+++ ThreadPool.h Sun Mar 4 04:32:07 2018
@@ -1,5 +1,18 @@
#pragma once
+#ifdef AFFINITY
+#if defined __sun__
+#include <sys/types.h>
+#include <sys/processor.h>
+#include <sys/procset.h>
+#include <unistd.h> /* For sysconf */
+#elif __linux__
+#include <cstdio> /* For fprintf */
+#include <sched.h>
+#endif
+#endif
+
+#include <cstddef> /* For std::size_t */
#include <functional>
#include <future>
#include <mutex>
@@ -14,10 +27,10 @@
private:
class ThreadWorker {
private:
- int m_id;
+ std::size_t m_id;
ThreadPool * m_pool;
public:
- ThreadWorker(ThreadPool * pool, const int id)
+ ThreadWorker(ThreadPool * pool, const std::size_t id)
: m_pool(pool), m_id(id) {
}
@@ -45,7 +58,7 @@
std::mutex m_conditional_mutex;
std::condition_variable m_conditional_lock;
public:
- ThreadPool(const int n_threads)
+ ThreadPool(const std::size_t n_threads)
: m_threads(std::vector<std::thread>(n_threads)), m_shutdown(false) {
}
@@ -57,7 +70,44 @@
// Inits thread pool
void init() {
- for (int i = 0; i < m_threads.size(); ++i) {
+ #if (defined __sun__ || defined __linux__) && defined AFFINITY
+ std::size_t v_cpu = 0;
+ std::size_t v_cpu_max = std::thread::hardware_concurrency() - 1;
+ #endif
+
+ #if defined __sun__ && defined AFFINITY
+ std::vector<processorid_t> v_cpu_id; /* Struct for CPU/core ID */
+
+ processorid_t i, cpuid_max;
+ cpuid_max = sysconf(_SC_CPUID_MAX);
+ for (i = 0; i <= cpuid_max; i++) {
+ if (p_online(i, P_STATUS) != -1) /* Get only online cores ID */
+ v_cpu_id.push_back(i);
+ }
+ #endif
+
+ for (std::size_t i = 0; i < m_threads.size(); ++i) {
+
+ #if (defined __sun__ || defined __linux__) && defined AFFINITY
+ if (v_cpu > v_cpu_max) {
+ v_cpu = 0;
+ }
+
+ #ifdef __sun__
+ processor_bind(P_LWPID, P_MYID, v_cpu_id[v_cpu], NULL);
+ #elif __linux__
+ cpu_set_t mask;
+ CPU_ZERO(&mask);
+ CPU_SET(v_cpu, &mask);
+ pthread_t thread = pthread_self();
+ if (pthread_setaffinity_np(thread, sizeof(cpu_set_t), &mask) != 0) {
+ fprintf(stderr, "Error setting thread affinity\n");
+ }
+ #endif
+
+ ++v_cpu;
+ #endif
+
m_threads[i] = std::thread(ThreadWorker(this, i));
}
}
--- SafeQueue.h Wed May 17 15:01:04 2017
+++ SafeQueue.h Sun Mar 4 04:32:07 2018
@@ -28,7 +28,7 @@
return m_queue.empty();
}
- int size() {
+ std::size_t size() {
std::unique_lock<std::mutex> lock(m_mutex);
return m_queue.size();
}