blob: 5eb7972bf59c40bb39eed860fce5bbe305700bfe [file] [log] [blame]
Marat Dukhan0a312192015-08-22 17:46:29 -04001/* Standard C headers */
2#include <stdint.h>
3#include <stdbool.h>
Marat Dukhan3a45d9a2015-08-23 22:25:19 -04004#include <stdlib.h>
Marat Dukhan0a312192015-08-22 17:46:29 -04005#include <string.h>
6#include <assert.h>
7
8/* POSIX headers */
9#include <pthread.h>
10#include <unistd.h>
11
12/* Library header */
13#include <pthreadpool.h>
14
15#define PTHREADPOOL_CACHELINE_SIZE 64
16#define PTHREADPOOL_CACHELINE_ALIGNED __attribute__((__aligned__(PTHREADPOOL_CACHELINE_SIZE)))
Marat Dukhanaf6468b2015-08-25 12:16:57 -040017
18#if (defined(__clang__) && (__has_extension(c_static_assert) || __has_feature(c_static_assert))) || \
19 (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 6)))
20 /* Static assert is supported by gcc >= 4.6 and modern clang */
21 #define PTHREADPOOL_STATIC_ASSERT(predicate, message) _Static_assert((predicate), message)
22#else
23 /* Dummy declaration for legacy compilers */
24 #define PTHREADPOOL_STATIC_ASSERT(predicate, message)
25#endif
Marat Dukhan0a312192015-08-22 17:46:29 -040026
27enum thread_state {
28 thread_state_idle,
29 thread_state_compute_1d,
30 thread_state_shutdown,
31};
32
33struct PTHREADPOOL_CACHELINE_ALIGNED thread_info {
34 /**
35 * Index of the first element in the work range.
36 * Before processing a new element the owning worker thread increments this value.
37 */
38 volatile size_t range_start;
39 /**
40 * Index of the element after the last element of the work range.
41 * Before processing a new element the stealing worker thread decrements this value.
42 */
43 volatile size_t range_end;
44 /**
45 * The number of elements in the work range.
46 * Due to race conditions range_length <= range_end - range_start.
47 * The owning worker thread must decrement this value before incrementing @a range_start.
48 * The stealing worker thread must decrement this value before decrementing @a range_end.
49 */
50 volatile size_t range_length;
51 /**
52 * The active state of the thread.
53 */
54 volatile enum thread_state state;
55 /**
56 * Thread number in the 0..threads_count-1 range.
57 */
58 size_t thread_number;
59 /**
60 * The pthread object corresponding to the thread.
61 */
62 pthread_t thread_object;
63 /**
64 * Condition variable used to wake up the thread.
65 * When the thread is idle, it waits on this condition variable.
66 */
67 pthread_cond_t wakeup_condvar;
68};
69
70PTHREADPOOL_STATIC_ASSERT(sizeof(struct thread_info) % PTHREADPOOL_CACHELINE_SIZE == 0, "thread_info structure must occupy an integer number of cache lines (64 bytes)");
71
72struct PTHREADPOOL_CACHELINE_ALIGNED pthreadpool {
73 /**
74 * The number of threads that signalled completion of an operation.
75 */
76 volatile size_t checkedin_threads;
77 /**
78 * The function to call for each item.
79 */
80 volatile pthreadpool_function_1d_t function;
81 /**
82 * The first argument to the item processing function.
83 */
84 void *volatile argument;
85 /**
86 * Serializes concurrent calls to @a pthreadpool_compute_* from different threads.
87 */
88 pthread_mutex_t execution_mutex;
89 /**
90 * Guards access to the @a checkedin_threads variable.
91 */
92 pthread_mutex_t barrier_mutex;
93 /**
94 * Condition variable to wait until all threads check in.
95 */
96 pthread_cond_t barrier_condvar;
97 /**
98 * Guards access to the @a state variables.
99 */
100 pthread_mutex_t state_mutex;
101 /**
102 * Condition variable to wait for change of @a state variable.
103 */
104 pthread_cond_t state_condvar;
105 /**
106 * The number of threads in the thread pool. Never changes after initialization.
107 */
108 size_t threads_count;
109 /**
110 * Thread information structures that immediately follow this structure.
111 */
112 struct thread_info threads[];
113};
114
115PTHREADPOOL_STATIC_ASSERT(sizeof(struct pthreadpool) % PTHREADPOOL_CACHELINE_SIZE == 0, "pthreadpool structure must occupy an integer number of cache lines (64 bytes)");
116
117static void checkin_worker_thread(struct pthreadpool* threadpool) {
118 pthread_mutex_lock(&threadpool->barrier_mutex);
119 const size_t checkedin_threads = threadpool->checkedin_threads + 1;
120 threadpool->checkedin_threads = checkedin_threads;
121 if (checkedin_threads == threadpool->threads_count) {
122 pthread_cond_signal(&threadpool->barrier_condvar);
123 }
124 pthread_mutex_unlock(&threadpool->barrier_mutex);
125}
126
127static void wait_worker_threads(struct pthreadpool* threadpool) {
128 if (threadpool->checkedin_threads != threadpool->threads_count) {
129 pthread_mutex_lock(&threadpool->barrier_mutex);
130 while (threadpool->checkedin_threads != threadpool->threads_count) {
131 pthread_cond_wait(&threadpool->barrier_condvar, &threadpool->barrier_mutex);
132 };
133 pthread_mutex_unlock(&threadpool->barrier_mutex);
134 }
135}
136
137static void wakeup_worker_threads(struct pthreadpool* threadpool) {
138 pthread_mutex_lock(&threadpool->state_mutex);
139 threadpool->checkedin_threads = 0; /* Locking of barrier_mutex not needed: readers are sleeping */
140 pthread_cond_broadcast(&threadpool->state_condvar);
141 pthread_mutex_unlock(&threadpool->state_mutex); /* Do wake up */
142}
143
144inline static bool atomic_decrement(volatile size_t* value) {
145 size_t actual_value = *value;
146 if (actual_value != 0) {
147 size_t expected_value;
148 do {
149 expected_value = actual_value;
150 const size_t new_value = actual_value - 1;
151 actual_value = __sync_val_compare_and_swap(value, expected_value, new_value);
152 } while ((actual_value != expected_value) && (actual_value != 0));
153 }
154 return actual_value != 0;
155}
156
157static void thread_compute_1d(struct pthreadpool* threadpool, struct thread_info* thread) {
158 const pthreadpool_function_1d_t function = threadpool->function;
159 void *const argument = threadpool->argument;
160 /* Process thread's own range of items */
161 size_t range_start = thread->range_start;
162 while (atomic_decrement(&thread->range_length)) {
163 function(argument, range_start++);
164 }
165 /* Done, now look for other threads' items to steal */
166 const size_t thread_number = thread->thread_number;
167 const size_t threads_count = threadpool->threads_count;
168 for (size_t tid = (thread_number + 1) % threads_count; tid != thread_number; tid = (tid + 1) % threads_count) {
169 struct thread_info* other_thread = &threadpool->threads[tid];
170 if (other_thread->state != thread_state_idle) {
171 while (atomic_decrement(&other_thread->range_length)) {
172 const size_t item_id = __sync_sub_and_fetch(&other_thread->range_end, 1);
173 function(argument, item_id);
174 }
175 }
176 }
177}
178
179static void* thread_main(void* arg) {
180 struct thread_info* thread = (struct thread_info*) arg;
181 struct pthreadpool* threadpool = ((struct pthreadpool*) (thread - thread->thread_number)) - 1;
182
183 /* Check in */
184 checkin_worker_thread(threadpool);
185
186 /* Monitor the state changes and act accordingly */
187 for (;;) {
188 /* Lock the state mutex */
189 pthread_mutex_lock(&threadpool->state_mutex);
190 /* Read the state */
191 enum thread_state state;
192 while ((state = thread->state) == thread_state_idle) {
193 /* Wait for state change */
194 pthread_cond_wait(&threadpool->state_condvar, &threadpool->state_mutex);
195 }
196 /* Read non-idle state */
197 pthread_mutex_unlock(&threadpool->state_mutex);
198 switch (state) {
199 case thread_state_compute_1d:
200 thread_compute_1d(threadpool, thread);
201 break;
202 case thread_state_shutdown:
203 return NULL;
204 case thread_state_idle:
205 /* To inhibit compiler warning */
206 break;
207 }
208 /* Notify the master thread that we finished processing */
209 thread->state = thread_state_idle;
210 checkin_worker_thread(threadpool);
211 };
212}
213
214struct pthreadpool* pthreadpool_create(size_t threads_count) {
215 if (threads_count == 0) {
216 threads_count = (size_t) sysconf(_SC_NPROCESSORS_ONLN);
217 }
Marat Dukhan3a45d9a2015-08-23 22:25:19 -0400218 struct pthreadpool* threadpool = NULL;
219 posix_memalign((void**) &threadpool, 64, sizeof(struct pthreadpool) + threads_count * sizeof(struct thread_info));
Marat Dukhan0a312192015-08-22 17:46:29 -0400220 memset(threadpool, 0, sizeof(struct pthreadpool) + threads_count * sizeof(struct thread_info));
221 threadpool->threads_count = threads_count;
222 pthread_mutex_init(&threadpool->execution_mutex, NULL);
223 pthread_mutex_init(&threadpool->barrier_mutex, NULL);
224 pthread_cond_init(&threadpool->barrier_condvar, NULL);
225 pthread_mutex_init(&threadpool->state_mutex, NULL);
226 pthread_cond_init(&threadpool->state_condvar, NULL);
227
228 for (size_t tid = 0; tid < threads_count; tid++) {
229 threadpool->threads[tid].thread_number = tid;
230 pthread_create(&threadpool->threads[tid].thread_object, NULL, &thread_main, &threadpool->threads[tid]);
231 }
232
233 /* Wait until all threads initialize */
234 wait_worker_threads(threadpool);
235 return threadpool;
236}
237
Marat Dukhan7b1f6e52015-08-25 11:24:08 -0400238size_t pthreadpool_get_threads_count(struct pthreadpool* threadpool) {
Marat Dukhan0a312192015-08-22 17:46:29 -0400239 return threadpool->threads_count;
240}
241
242static inline size_t multiply_divide(size_t a, size_t b, size_t d) {
243 #if defined(__SIZEOF_SIZE_T__) && (__SIZEOF_SIZE_T__ == 4)
244 return (size_t) (((uint64_t) a) * ((uint64_t) b)) / ((uint64_t) d);
245 #elif defined(__SIZEOF_SIZE_T__) && (__SIZEOF_SIZE_T__ == 8)
Marat Dukhanc058bd32015-08-23 22:24:48 -0400246 return (size_t) (((__uint128_t) a) * ((__uint128_t) b)) / ((__uint128_t) d);
Marat Dukhan0a312192015-08-22 17:46:29 -0400247 #else
248 #error "Unsupported platform"
249 #endif
250}
251
252void pthreadpool_compute_1d(
253 struct pthreadpool* threadpool,
254 pthreadpool_function_1d_t function,
255 void* argument,
256 size_t items)
257{
258 /* Protect the global threadpool structures */
259 pthread_mutex_lock(&threadpool->execution_mutex);
260
261 /* Spread the work between threads */
262 for (size_t tid = 0; tid < threadpool->threads_count; tid++) {
263 struct thread_info* thread = &threadpool->threads[tid];
264 thread->range_start = multiply_divide(items, tid, threadpool->threads_count);
265 thread->range_end = multiply_divide(items, tid + 1, threadpool->threads_count);
266 thread->range_length = thread->range_end - thread->range_start;
267 thread->state = thread_state_compute_1d;
268 }
269
270 /* Setup global arguments */
271 threadpool->function = function;
272 threadpool->argument = argument;
273
274 /* Wake up the threads */
275 wakeup_worker_threads(threadpool);
276
277 /* Wait until the threads finish computation */
278 wait_worker_threads(threadpool);
279
280 /* Unprotect the global threadpool structures */
281 pthread_mutex_unlock(&threadpool->execution_mutex);
282}
283
284void pthreadpool_destroy(struct pthreadpool* threadpool) {
285 /* Update threads' states */
286 for (size_t tid = 0; tid < threadpool->threads_count; tid++) {
287 threadpool->threads[tid].state = thread_state_shutdown;
288 }
289
290 /* Wake up the threads */
291 wakeup_worker_threads(threadpool);
292
293 /* Wait until all threads return */
294 for (size_t tid = 0; tid < threadpool->threads_count; tid++) {
295 pthread_join(threadpool->threads[tid].thread_object, NULL);
296 }
297
298 /* Release resources */
299 pthread_mutex_destroy(&threadpool->execution_mutex);
300 pthread_mutex_destroy(&threadpool->barrier_mutex);
301 pthread_cond_destroy(&threadpool->barrier_condvar);
302 pthread_mutex_destroy(&threadpool->state_mutex);
303 pthread_cond_destroy(&threadpool->state_condvar);
304 free(threadpool);
305}