blob: e97a56c07446ba1eba763e8a2bd616bdaf6e1332 [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
Marat Dukhan1325d6e2016-07-03 13:13:16 -040012/* Dependencies */
13#include <fxdiv.h>
14
Marat Dukhan0a312192015-08-22 17:46:29 -040015/* Library header */
16#include <pthreadpool.h>
17
18#define PTHREADPOOL_CACHELINE_SIZE 64
19#define PTHREADPOOL_CACHELINE_ALIGNED __attribute__((__aligned__(PTHREADPOOL_CACHELINE_SIZE)))
Marat Dukhanaf6468b2015-08-25 12:16:57 -040020
Marat Dukhana04943a2015-08-25 12:41:05 -040021#if defined(__clang__)
22 #if __has_extension(c_static_assert) || __has_feature(c_static_assert)
23 #define PTHREADPOOL_STATIC_ASSERT(predicate, message) _Static_assert((predicate), message)
24 #else
25 #define PTHREADPOOL_STATIC_ASSERT(predicate, message)
26 #endif
27#elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))
28 /* Static assert is supported by gcc >= 4.6 */
Marat Dukhanaf6468b2015-08-25 12:16:57 -040029 #define PTHREADPOOL_STATIC_ASSERT(predicate, message) _Static_assert((predicate), message)
30#else
Marat Dukhanaf6468b2015-08-25 12:16:57 -040031 #define PTHREADPOOL_STATIC_ASSERT(predicate, message)
32#endif
Marat Dukhan0a312192015-08-22 17:46:29 -040033
Marat Dukhanad0ca6a2015-10-16 03:15:19 -040034static inline size_t multiply_divide(size_t a, size_t b, size_t d) {
35 #if defined(__SIZEOF_SIZE_T__) && (__SIZEOF_SIZE_T__ == 4)
36 return (size_t) (((uint64_t) a) * ((uint64_t) b)) / ((uint64_t) d);
37 #elif defined(__SIZEOF_SIZE_T__) && (__SIZEOF_SIZE_T__ == 8)
38 return (size_t) (((__uint128_t) a) * ((__uint128_t) b)) / ((__uint128_t) d);
39 #else
40 #error "Unsupported platform"
41 #endif
42}
43
44static inline size_t divide_round_up(size_t dividend, size_t divisor) {
45 if (dividend % divisor == 0) {
46 return dividend / divisor;
47 } else {
48 return dividend / divisor + 1;
49 }
50}
51
52static inline size_t min(size_t a, size_t b) {
53 return a < b ? a : b;
54}
55
Marat Dukhan0a312192015-08-22 17:46:29 -040056enum thread_state {
57 thread_state_idle,
58 thread_state_compute_1d,
59 thread_state_shutdown,
60};
61
62struct PTHREADPOOL_CACHELINE_ALIGNED thread_info {
63 /**
64 * Index of the first element in the work range.
65 * Before processing a new element the owning worker thread increments this value.
66 */
67 volatile size_t range_start;
68 /**
69 * Index of the element after the last element of the work range.
70 * Before processing a new element the stealing worker thread decrements this value.
71 */
72 volatile size_t range_end;
73 /**
74 * The number of elements in the work range.
75 * Due to race conditions range_length <= range_end - range_start.
76 * The owning worker thread must decrement this value before incrementing @a range_start.
77 * The stealing worker thread must decrement this value before decrementing @a range_end.
78 */
79 volatile size_t range_length;
80 /**
81 * The active state of the thread.
82 */
83 volatile enum thread_state state;
84 /**
85 * Thread number in the 0..threads_count-1 range.
86 */
87 size_t thread_number;
88 /**
89 * The pthread object corresponding to the thread.
90 */
91 pthread_t thread_object;
92 /**
93 * Condition variable used to wake up the thread.
94 * When the thread is idle, it waits on this condition variable.
95 */
96 pthread_cond_t wakeup_condvar;
97};
98
99PTHREADPOOL_STATIC_ASSERT(sizeof(struct thread_info) % PTHREADPOOL_CACHELINE_SIZE == 0, "thread_info structure must occupy an integer number of cache lines (64 bytes)");
100
101struct PTHREADPOOL_CACHELINE_ALIGNED pthreadpool {
102 /**
103 * The number of threads that signalled completion of an operation.
104 */
105 volatile size_t checkedin_threads;
106 /**
107 * The function to call for each item.
108 */
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400109 volatile void* function;
Marat Dukhan0a312192015-08-22 17:46:29 -0400110 /**
111 * The first argument to the item processing function.
112 */
113 void *volatile argument;
114 /**
115 * Serializes concurrent calls to @a pthreadpool_compute_* from different threads.
116 */
117 pthread_mutex_t execution_mutex;
118 /**
119 * Guards access to the @a checkedin_threads variable.
120 */
121 pthread_mutex_t barrier_mutex;
122 /**
123 * Condition variable to wait until all threads check in.
124 */
125 pthread_cond_t barrier_condvar;
126 /**
127 * Guards access to the @a state variables.
128 */
129 pthread_mutex_t state_mutex;
130 /**
131 * Condition variable to wait for change of @a state variable.
132 */
133 pthread_cond_t state_condvar;
134 /**
135 * The number of threads in the thread pool. Never changes after initialization.
136 */
137 size_t threads_count;
138 /**
139 * Thread information structures that immediately follow this structure.
140 */
141 struct thread_info threads[];
142};
143
144PTHREADPOOL_STATIC_ASSERT(sizeof(struct pthreadpool) % PTHREADPOOL_CACHELINE_SIZE == 0, "pthreadpool structure must occupy an integer number of cache lines (64 bytes)");
145
146static void checkin_worker_thread(struct pthreadpool* threadpool) {
147 pthread_mutex_lock(&threadpool->barrier_mutex);
148 const size_t checkedin_threads = threadpool->checkedin_threads + 1;
149 threadpool->checkedin_threads = checkedin_threads;
150 if (checkedin_threads == threadpool->threads_count) {
151 pthread_cond_signal(&threadpool->barrier_condvar);
152 }
153 pthread_mutex_unlock(&threadpool->barrier_mutex);
154}
155
156static void wait_worker_threads(struct pthreadpool* threadpool) {
157 if (threadpool->checkedin_threads != threadpool->threads_count) {
158 pthread_mutex_lock(&threadpool->barrier_mutex);
159 while (threadpool->checkedin_threads != threadpool->threads_count) {
160 pthread_cond_wait(&threadpool->barrier_condvar, &threadpool->barrier_mutex);
161 };
162 pthread_mutex_unlock(&threadpool->barrier_mutex);
163 }
164}
165
Marat Dukhan0a312192015-08-22 17:46:29 -0400166inline static bool atomic_decrement(volatile size_t* value) {
167 size_t actual_value = *value;
168 if (actual_value != 0) {
169 size_t expected_value;
170 do {
171 expected_value = actual_value;
172 const size_t new_value = actual_value - 1;
173 actual_value = __sync_val_compare_and_swap(value, expected_value, new_value);
174 } while ((actual_value != expected_value) && (actual_value != 0));
175 }
176 return actual_value != 0;
177}
178
179static void thread_compute_1d(struct pthreadpool* threadpool, struct thread_info* thread) {
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400180 const pthreadpool_function_1d_t function = (pthreadpool_function_1d_t) threadpool->function;
Marat Dukhan0a312192015-08-22 17:46:29 -0400181 void *const argument = threadpool->argument;
182 /* Process thread's own range of items */
183 size_t range_start = thread->range_start;
184 while (atomic_decrement(&thread->range_length)) {
185 function(argument, range_start++);
186 }
187 /* Done, now look for other threads' items to steal */
188 const size_t thread_number = thread->thread_number;
189 const size_t threads_count = threadpool->threads_count;
190 for (size_t tid = (thread_number + 1) % threads_count; tid != thread_number; tid = (tid + 1) % threads_count) {
191 struct thread_info* other_thread = &threadpool->threads[tid];
192 if (other_thread->state != thread_state_idle) {
193 while (atomic_decrement(&other_thread->range_length)) {
194 const size_t item_id = __sync_sub_and_fetch(&other_thread->range_end, 1);
195 function(argument, item_id);
196 }
197 }
198 }
199}
200
201static void* thread_main(void* arg) {
202 struct thread_info* thread = (struct thread_info*) arg;
203 struct pthreadpool* threadpool = ((struct pthreadpool*) (thread - thread->thread_number)) - 1;
204
205 /* Check in */
206 checkin_worker_thread(threadpool);
207
208 /* Monitor the state changes and act accordingly */
209 for (;;) {
210 /* Lock the state mutex */
211 pthread_mutex_lock(&threadpool->state_mutex);
212 /* Read the state */
213 enum thread_state state;
214 while ((state = thread->state) == thread_state_idle) {
215 /* Wait for state change */
216 pthread_cond_wait(&threadpool->state_condvar, &threadpool->state_mutex);
217 }
218 /* Read non-idle state */
219 pthread_mutex_unlock(&threadpool->state_mutex);
220 switch (state) {
221 case thread_state_compute_1d:
222 thread_compute_1d(threadpool, thread);
223 break;
224 case thread_state_shutdown:
225 return NULL;
226 case thread_state_idle:
227 /* To inhibit compiler warning */
228 break;
229 }
230 /* Notify the master thread that we finished processing */
231 thread->state = thread_state_idle;
232 checkin_worker_thread(threadpool);
233 };
234}
235
236struct pthreadpool* pthreadpool_create(size_t threads_count) {
237 if (threads_count == 0) {
238 threads_count = (size_t) sysconf(_SC_NPROCESSORS_ONLN);
239 }
Marat Dukhan17747d72016-09-13 15:29:02 -0400240#if !defined(__ANDROID__)
Marat Dukhan3a45d9a2015-08-23 22:25:19 -0400241 struct pthreadpool* threadpool = NULL;
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400242 if (posix_memalign((void**) &threadpool, 64, sizeof(struct pthreadpool) + threads_count * sizeof(struct thread_info)) != 0) {
Marat Dukhan17747d72016-09-13 15:29:02 -0400243#else
244 /*
245 * Android didn't get posix_memalign until API level 17 (Android 4.2).
246 * Use (otherwise obsolete) memalign function on Android platform.
247 */
248 struct pthreadpool* threadpool = memalign(64, sizeof(struct pthreadpool) + threads_count * sizeof(struct thread_info));
249 if (threadpool == NULL) {
250#endif
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400251 return NULL;
252 }
Marat Dukhan0a312192015-08-22 17:46:29 -0400253 memset(threadpool, 0, sizeof(struct pthreadpool) + threads_count * sizeof(struct thread_info));
254 threadpool->threads_count = threads_count;
255 pthread_mutex_init(&threadpool->execution_mutex, NULL);
256 pthread_mutex_init(&threadpool->barrier_mutex, NULL);
257 pthread_cond_init(&threadpool->barrier_condvar, NULL);
258 pthread_mutex_init(&threadpool->state_mutex, NULL);
259 pthread_cond_init(&threadpool->state_condvar, NULL);
260
261 for (size_t tid = 0; tid < threads_count; tid++) {
262 threadpool->threads[tid].thread_number = tid;
263 pthread_create(&threadpool->threads[tid].thread_object, NULL, &thread_main, &threadpool->threads[tid]);
264 }
265
266 /* Wait until all threads initialize */
267 wait_worker_threads(threadpool);
268 return threadpool;
269}
270
Marat Dukhan7b1f6e52015-08-25 11:24:08 -0400271size_t pthreadpool_get_threads_count(struct pthreadpool* threadpool) {
Marat Dukhan0a312192015-08-22 17:46:29 -0400272 return threadpool->threads_count;
273}
274
Marat Dukhan0a312192015-08-22 17:46:29 -0400275void pthreadpool_compute_1d(
276 struct pthreadpool* threadpool,
277 pthreadpool_function_1d_t function,
278 void* argument,
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400279 size_t range)
Marat Dukhan0a312192015-08-22 17:46:29 -0400280{
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400281 if (threadpool == NULL) {
282 /* No thread pool provided: execute function sequentially on the calling thread */
283 for (size_t i = 0; i < range; i++) {
284 function(argument, i);
285 }
286 } else {
287 /* Protect the global threadpool structures */
288 pthread_mutex_lock(&threadpool->execution_mutex);
Marat Dukhan0a312192015-08-22 17:46:29 -0400289
Marat Dukhanfa98b4b2015-11-06 18:19:31 -0500290 /* Lock the state variables to ensure that threads don't start processing before they observe complete state */
291 pthread_mutex_lock(&threadpool->state_mutex);
292
293 /* Setup global arguments */
294 threadpool->function = function;
295 threadpool->argument = argument;
296
Marat Dukhan630dfb62017-03-05 17:42:04 -0500297 /* Locking of barrier_mutex not needed: readers are sleeping on state_condvar */
298 threadpool->checkedin_threads = 0;
299
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400300 /* Spread the work between threads */
301 for (size_t tid = 0; tid < threadpool->threads_count; tid++) {
302 struct thread_info* thread = &threadpool->threads[tid];
303 thread->range_start = multiply_divide(range, tid, threadpool->threads_count);
304 thread->range_end = multiply_divide(range, tid + 1, threadpool->threads_count);
305 thread->range_length = thread->range_end - thread->range_start;
306 thread->state = thread_state_compute_1d;
307 }
308
Marat Dukhanfa98b4b2015-11-06 18:19:31 -0500309 /* Unlock the state variables before waking up the threads for better performance */
310 pthread_mutex_unlock(&threadpool->state_mutex);
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400311
312 /* Wake up the threads */
Marat Dukhan630dfb62017-03-05 17:42:04 -0500313 pthread_cond_broadcast(&threadpool->state_condvar);
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400314
315 /* Wait until the threads finish computation */
316 wait_worker_threads(threadpool);
317
318 /* Unprotect the global threadpool structures */
319 pthread_mutex_unlock(&threadpool->execution_mutex);
Marat Dukhan0a312192015-08-22 17:46:29 -0400320 }
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400321}
Marat Dukhan0a312192015-08-22 17:46:29 -0400322
Marat Dukhane76282f2015-11-02 17:47:04 -0500323struct compute_1d_tiled_context {
324 pthreadpool_function_1d_tiled_t function;
325 void* argument;
326 size_t range;
327 size_t tile;
328};
329
330static void compute_1d_tiled(const struct compute_1d_tiled_context* context, size_t linear_index) {
331 const size_t tile_index = linear_index;
332 const size_t index = tile_index * context->tile;
333 const size_t tile = min(context->tile, context->range - index);
334 context->function(context->argument, index, tile);
335}
336
337void pthreadpool_compute_1d_tiled(
338 pthreadpool_t threadpool,
339 pthreadpool_function_1d_tiled_t function,
340 void* argument,
341 size_t range,
342 size_t tile)
343{
Marat Dukhanf3c8d732016-07-11 15:44:51 -0400344 if (threadpool == NULL) {
345 /* No thread pool provided: execute function sequentially on the calling thread */
346 for (size_t i = 0; i < range; i += tile) {
347 function(argument, i, min(range - i, tile));
348 }
349 } else {
350 /* Execute in parallel on the thread pool using linearized index */
351 const size_t tile_range = divide_round_up(range, tile);
352 struct compute_1d_tiled_context context = {
353 .function = function,
354 .argument = argument,
355 .range = range,
356 .tile = tile
357 };
358 pthreadpool_compute_1d(threadpool, (pthreadpool_function_1d_t) compute_1d_tiled, &context, tile_range);
359 }
Marat Dukhane76282f2015-11-02 17:47:04 -0500360}
361
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400362struct compute_2d_context {
363 pthreadpool_function_2d_t function;
364 void* argument;
Marat Dukhan1325d6e2016-07-03 13:13:16 -0400365 struct fxdiv_divisor_size_t range_j;
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400366};
Marat Dukhan0a312192015-08-22 17:46:29 -0400367
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400368static void compute_2d(const struct compute_2d_context* context, size_t linear_index) {
Marat Dukhan1325d6e2016-07-03 13:13:16 -0400369 const struct fxdiv_divisor_size_t range_j = context->range_j;
370 const struct fxdiv_result_size_t index = fxdiv_divide_size_t(linear_index, range_j);
371 context->function(context->argument, index.quotient, index.remainder);
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400372}
Marat Dukhan0a312192015-08-22 17:46:29 -0400373
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400374void pthreadpool_compute_2d(
375 struct pthreadpool* threadpool,
376 pthreadpool_function_2d_t function,
377 void* argument,
378 size_t range_i,
379 size_t range_j)
380{
Marat Dukhanf3c8d732016-07-11 15:44:51 -0400381 if (threadpool == NULL) {
382 /* No thread pool provided: execute function sequentially on the calling thread */
383 for (size_t i = 0; i < range_i; i++) {
384 for (size_t j = 0; j < range_j; j++) {
385 function(argument, i, j);
386 }
387 }
388 } else {
389 /* Execute in parallel on the thread pool using linearized index */
390 struct compute_2d_context context = {
391 .function = function,
392 .argument = argument,
393 .range_j = fxdiv_init_size_t(range_j)
394 };
395 pthreadpool_compute_1d(threadpool, (pthreadpool_function_1d_t) compute_2d, &context, range_i * range_j);
396 }
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400397}
Marat Dukhan0a312192015-08-22 17:46:29 -0400398
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400399struct compute_2d_tiled_context {
400 pthreadpool_function_2d_tiled_t function;
401 void* argument;
Marat Dukhan1325d6e2016-07-03 13:13:16 -0400402 struct fxdiv_divisor_size_t tile_range_j;
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400403 size_t range_i;
404 size_t range_j;
405 size_t tile_i;
406 size_t tile_j;
407};
408
409static void compute_2d_tiled(const struct compute_2d_tiled_context* context, size_t linear_index) {
Marat Dukhan1325d6e2016-07-03 13:13:16 -0400410 const struct fxdiv_divisor_size_t tile_range_j = context->tile_range_j;
411 const struct fxdiv_result_size_t tile_index = fxdiv_divide_size_t(linear_index, tile_range_j);
412 const size_t max_tile_i = context->tile_i;
413 const size_t max_tile_j = context->tile_j;
414 const size_t index_i = tile_index.quotient * max_tile_i;
415 const size_t index_j = tile_index.remainder * max_tile_j;
416 const size_t tile_i = min(max_tile_i, context->range_i - index_i);
417 const size_t tile_j = min(max_tile_j, context->range_j - index_j);
Marat Dukhanad0ca6a2015-10-16 03:15:19 -0400418 context->function(context->argument, index_i, index_j, tile_i, tile_j);
419}
420
421void pthreadpool_compute_2d_tiled(
422 pthreadpool_t threadpool,
423 pthreadpool_function_2d_tiled_t function,
424 void* argument,
425 size_t range_i,
426 size_t range_j,
427 size_t tile_i,
428 size_t tile_j)
429{
Marat Dukhanf3c8d732016-07-11 15:44:51 -0400430 if (threadpool == NULL) {
431 /* No thread pool provided: execute function sequentially on the calling thread */
432 for (size_t i = 0; i < range_i; i += tile_i) {
433 for (size_t j = 0; j < range_j; j += tile_j) {
434 function(argument, i, j, min(range_i - i, tile_i), min(range_j - j, tile_j));
435 }
436 }
437 } else {
438 /* Execute in parallel on the thread pool using linearized index */
439 const size_t tile_range_i = divide_round_up(range_i, tile_i);
440 const size_t tile_range_j = divide_round_up(range_j, tile_j);
441 struct compute_2d_tiled_context context = {
442 .function = function,
443 .argument = argument,
444 .tile_range_j = fxdiv_init_size_t(tile_range_j),
445 .range_i = range_i,
446 .range_j = range_j,
447 .tile_i = tile_i,
448 .tile_j = tile_j
449 };
450 pthreadpool_compute_1d(threadpool, (pthreadpool_function_1d_t) compute_2d_tiled, &context, tile_range_i * tile_range_j);
451 }
Marat Dukhan0a312192015-08-22 17:46:29 -0400452}
453
454void pthreadpool_destroy(struct pthreadpool* threadpool) {
Marat Dukhaneef99d42017-03-05 17:59:07 -0500455 if (threadpool != NULL) {
456 /* Lock the state variables to ensure that threads don't start processing before they observe complete state */
457 pthread_mutex_lock(&threadpool->state_mutex);
Marat Dukhan630dfb62017-03-05 17:42:04 -0500458
Marat Dukhaneef99d42017-03-05 17:59:07 -0500459 /* Locking of barrier_mutex not needed: readers are sleeping on state_condvar */
460 threadpool->checkedin_threads = 0;
Marat Dukhan630dfb62017-03-05 17:42:04 -0500461
Marat Dukhaneef99d42017-03-05 17:59:07 -0500462 /* Update threads' states */
463 for (size_t tid = 0; tid < threadpool->threads_count; tid++) {
464 threadpool->threads[tid].state = thread_state_shutdown;
465 }
466
467 /* Wake up worker threads */
468 pthread_cond_broadcast(&threadpool->state_condvar);
469
470 /* Commit the state changes and let workers start processing */
471 pthread_mutex_unlock(&threadpool->state_mutex);
472
473 /* Wait until all threads return */
474 for (size_t tid = 0; tid < threadpool->threads_count; tid++) {
475 pthread_join(threadpool->threads[tid].thread_object, NULL);
476 }
477
478 /* Release resources */
479 pthread_mutex_destroy(&threadpool->execution_mutex);
480 pthread_mutex_destroy(&threadpool->barrier_mutex);
481 pthread_cond_destroy(&threadpool->barrier_condvar);
482 pthread_mutex_destroy(&threadpool->state_mutex);
483 pthread_cond_destroy(&threadpool->state_condvar);
484 free(threadpool);
Marat Dukhan0a312192015-08-22 17:46:29 -0400485 }
Marat Dukhan0a312192015-08-22 17:46:29 -0400486}