aboutsummaryrefslogtreecommitdiff
path: root/src/threadpool-pthreads.c
blob: 6c6a6d441615e901513450408d3c312cd7b4143c (plain)
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
/* Standard C headers */
#include <stdatomic.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

/* POSIX headers */
#include <pthread.h>
#include <unistd.h>

/* Futex-specific headers */
#ifndef PTHREADPOOL_USE_FUTEX
	#if defined(__linux__)
		#define PTHREADPOOL_USE_FUTEX 1
		#include <sys/syscall.h>
		#include <linux/futex.h>

		/* Old Android NDKs do not define SYS_futex and FUTEX_PRIVATE_FLAG */
		#ifndef SYS_futex
			#define SYS_futex __NR_futex
		#endif
		#ifndef FUTEX_PRIVATE_FLAG
			#define FUTEX_PRIVATE_FLAG 128
		#endif
	#elif defined(__native_client__)
		#define PTHREADPOOL_USE_FUTEX 1
		#include <irt.h>
	#else
		#define PTHREADPOOL_USE_FUTEX 0
	#endif
#endif

/* Dependencies */
#include <fxdiv.h>

/* Library header */
#include <pthreadpool.h>

/* Internal headers */
#include "threadpool-utils.h"

/* Number of iterations in spin-wait loop before going into futex/mutex wait */
#define PTHREADPOOL_SPIN_WAIT_ITERATIONS 1000000

#define PTHREADPOOL_CACHELINE_SIZE 64
#define PTHREADPOOL_CACHELINE_ALIGNED __attribute__((__aligned__(PTHREADPOOL_CACHELINE_SIZE)))

#if defined(__clang__)
	#if __has_extension(c_static_assert) || __has_feature(c_static_assert)
		#define PTHREADPOOL_STATIC_ASSERT(predicate, message) _Static_assert((predicate), message)
	#else
		#define PTHREADPOOL_STATIC_ASSERT(predicate, message)
	#endif
#elif defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))
	/* Static assert is supported by gcc >= 4.6 */
	#define PTHREADPOOL_STATIC_ASSERT(predicate, message) _Static_assert((predicate), message)
#else
	#define PTHREADPOOL_STATIC_ASSERT(predicate, message)
#endif

static inline size_t multiply_divide(size_t a, size_t b, size_t d) {
	#if defined(__SIZEOF_SIZE_T__) && (__SIZEOF_SIZE_T__ == 4)
		return (size_t) (((uint64_t) a) * ((uint64_t) b)) / ((uint64_t) d);
	#elif defined(__SIZEOF_SIZE_T__) && (__SIZEOF_SIZE_T__ == 8)
		return (size_t) (((__uint128_t) a) * ((__uint128_t) b)) / ((__uint128_t) d);
	#else
		#error "Unsupported platform"
	#endif
}

static inline size_t divide_round_up(size_t dividend, size_t divisor) {
	if (dividend % divisor == 0) {
		return dividend / divisor;
	} else {
		return dividend / divisor + 1;
	}
}

static inline size_t min(size_t a, size_t b) {
	return a < b ? a : b;
}

#if PTHREADPOOL_USE_FUTEX
	#if defined(__linux__)
		static int futex_wait(_Atomic uint32_t* address, uint32_t value) {
			return syscall(SYS_futex, address, FUTEX_WAIT | FUTEX_PRIVATE_FLAG, value, NULL);
		}

		static int futex_wake_all(_Atomic uint32_t* address) {
			return syscall(SYS_futex, address, FUTEX_WAKE | FUTEX_PRIVATE_FLAG, INT_MAX);
		}
	#elif defined(__native_client__)
		static struct nacl_irt_futex nacl_irt_futex = { 0 };
		static pthread_once_t nacl_init_guard = PTHREAD_ONCE_INIT;
		static void nacl_init(void) {
			nacl_interface_query(NACL_IRT_FUTEX_v0_1, &nacl_irt_futex, sizeof(nacl_irt_futex));
		}

		static int futex_wait(_Atomic uint32_t* address, uint32_t value) {
			return nacl_irt_futex.futex_wait_abs((_Atomic int*) address, (int) value, NULL);
		}

		static int futex_wake_all(_Atomic uint32_t* address) {
			int count;
			return nacl_irt_futex.futex_wake((_Atomic int*) address, INT_MAX, &count);
		}
	#else
		#error "Platform-specific implementation of futex_wait and futex_wake_all required"
	#endif
#endif

#define THREADPOOL_COMMAND_MASK UINT32_C(0x7FFFFFFF)

enum threadpool_command {
	threadpool_command_init,
	threadpool_command_compute_1d,
	threadpool_command_shutdown,
};

struct PTHREADPOOL_CACHELINE_ALIGNED thread_info {
	/**
	 * Index of the first element in the work range.
	 * Before processing a new element the owning worker thread increments this value.
	 */
	atomic_size_t range_start;
	/**
	 * Index of the element after the last element of the work range.
	 * Before processing a new element the stealing worker thread decrements this value.
	 */
	atomic_size_t range_end;
	/**
	 * The number of elements in the work range.
	 * Due to race conditions range_length <= range_end - range_start.
	 * The owning worker thread must decrement this value before incrementing @a range_start.
	 * The stealing worker thread must decrement this value before decrementing @a range_end.
	 */
	atomic_size_t range_length;
	/**
	 * Thread number in the 0..threads_count-1 range.
	 */
	size_t thread_number;
	/**
	 * The pthread object corresponding to the thread.
	 */
	pthread_t thread_object;
	/**
	 * Condition variable used to wake up the thread.
	 * When the thread is idle, it waits on this condition variable.
	 */
	pthread_cond_t wakeup_condvar;
};

PTHREADPOOL_STATIC_ASSERT(sizeof(struct thread_info) % PTHREADPOOL_CACHELINE_SIZE == 0, "thread_info structure must occupy an integer number of cache lines (64 bytes)");

struct PTHREADPOOL_CACHELINE_ALIGNED pthreadpool {
	/**
	 * The number of threads that are processing an operation.
	 */
	atomic_size_t active_threads;
#if PTHREADPOOL_USE_FUTEX
	/**
	 * Indicates if there are active threads.
	 * Only two values are possible:
	 * - has_active_threads == 0 if active_threads == 0
	 * - has_active_threads == 1 if active_threads != 0
	 */
	_Atomic uint32_t has_active_threads;
#endif
	/**
	 * The last command submitted to the thread pool.
	 */
	_Atomic uint32_t command;
	/**
	 * The function to call for each item.
	 */
	void *_Atomic task;
	/**
	 * The first argument to the item processing function.
	 */
	void *_Atomic argument;
	/**
	 * Copy of the flags passed to parallelization function.
	 */
	_Atomic uint32_t flags;
	/**
	 * Serializes concurrent calls to @a pthreadpool_parallelize_* from different threads.
	 */
	pthread_mutex_t execution_mutex;
#if !PTHREADPOOL_USE_FUTEX
	/**
	 * Guards access to the @a active_threads variable.
	 */
	pthread_mutex_t completion_mutex;
	/**
	 * Condition variable to wait until all threads complete an operation (until @a active_threads is zero).
	 */
	pthread_cond_t completion_condvar;
	/**
	 * Guards access to the @a command variable.
	 */
	pthread_mutex_t command_mutex;
	/**
	 * Condition variable to wait for change of the @a command variable.
	 */
	pthread_cond_t command_condvar;
#endif
	/**
	 * The number of threads in the thread pool. Never changes after initialization.
	 */
	size_t threads_count;
	/**
	 * Thread information structures that immediately follow this structure.
	 */
	struct thread_info threads[];
};

PTHREADPOOL_STATIC_ASSERT(sizeof(struct pthreadpool) % PTHREADPOOL_CACHELINE_SIZE == 0, "pthreadpool structure must occupy an integer number of cache lines (64 bytes)");

static void checkin_worker_thread(struct pthreadpool* threadpool) {
	#if PTHREADPOOL_USE_FUTEX
		if (atomic_fetch_sub_explicit(&threadpool->active_threads, 1, memory_order_relaxed) == 1) {
			atomic_store_explicit(&threadpool->has_active_threads, 0, memory_order_release);
			futex_wake_all(&threadpool->has_active_threads);
		}
	#else
		pthread_mutex_lock(&threadpool->completion_mutex);
		if (atomic_fetch_sub_explicit(&threadpool->active_threads, 1, memory_order_relaxed) == 1) {
			pthread_cond_signal(&threadpool->completion_condvar);
		}
		pthread_mutex_unlock(&threadpool->completion_mutex);
	#endif
}

static void wait_worker_threads(struct pthreadpool* threadpool) {
	/* Initial check */
	#if PTHREADPOOL_USE_FUTEX
		uint32_t has_active_threads = atomic_load_explicit(&threadpool->has_active_threads, memory_order_relaxed);
		if (has_active_threads == 0) {
			return;
		}
	#else
		size_t active_threads = atomic_load_explicit(&threadpool->active_threads, memory_order_relaxed);
		if (active_threads == 0) {
			return;
		}
	#endif

	/* Spin-wait */
	for (uint32_t i = PTHREADPOOL_SPIN_WAIT_ITERATIONS; i != 0; i--) {
		/* This fence serves as a sleep instruction */
		atomic_thread_fence(memory_order_acquire);

		#if PTHREADPOOL_USE_FUTEX
			has_active_threads = atomic_load_explicit(&threadpool->has_active_threads, memory_order_relaxed);
			if (has_active_threads == 0) {
				return;
			}
		#else
			active_threads = atomic_load_explicit(&threadpool->active_threads, memory_order_relaxed);
			if (active_threads == 0) {
				return;
			}
		#endif
	}

	/* Fall-back to mutex/futex wait */
	#if PTHREADPOOL_USE_FUTEX
		while ((has_active_threads = atomic_load(&threadpool->has_active_threads)) != 0) {
			futex_wait(&threadpool->has_active_threads, 1);
		}
	#else
		pthread_mutex_lock(&threadpool->completion_mutex);
		while (atomic_load_explicit(&threadpool->active_threads, memory_order_relaxed) != 0) {
			pthread_cond_wait(&threadpool->completion_condvar, &threadpool->completion_mutex);
		};
		pthread_mutex_unlock(&threadpool->completion_mutex);
	#endif
}

inline static bool atomic_decrement(atomic_size_t* value) {
	size_t actual_value = atomic_load_explicit(value, memory_order_relaxed);
	if (actual_value == 0) {
		return false;
	}
	while (!atomic_compare_exchange_weak_explicit(
		value, &actual_value, actual_value - 1, memory_order_relaxed, memory_order_relaxed))
	{
		if (actual_value == 0) {
			return false;
		}
	}
	return true;
}

inline static size_t modulo_decrement(uint32_t i, uint32_t n) {
	/* Wrap modulo n, if needed */
	if (i == 0) {
		i = n;
	}
	/* Decrement input variable */
	return i - 1;
}

static void thread_parallelize_1d(struct pthreadpool* threadpool, struct thread_info* thread) {
	const pthreadpool_task_1d_t task = (pthreadpool_task_1d_t) atomic_load_explicit(&threadpool->task, memory_order_relaxed);
	void *const argument = atomic_load_explicit(&threadpool->argument, memory_order_relaxed);
	/* Process thread's own range of items */
	size_t range_start = atomic_load_explicit(&thread->range_start, memory_order_relaxed);
	while (atomic_decrement(&thread->range_length)) {
		task(argument, range_start++);
	}

	/* There still may be other threads with work */
	const size_t thread_number = thread->thread_number;
	const size_t threads_count = threadpool->threads_count;
	for (size_t tid = modulo_decrement(thread_number, threads_count);
		tid != thread_number;
		tid = modulo_decrement(tid, threads_count))
	{
		struct thread_info* other_thread = &threadpool->threads[tid];
		while (atomic_decrement(&other_thread->range_length)) {
			const size_t item_id = atomic_fetch_sub_explicit(&other_thread->range_end, 1, memory_order_relaxed) - 1;
			task(argument, item_id);
		}
	}
	atomic_thread_fence(memory_order_release);
}

static uint32_t wait_for_new_command(
	struct pthreadpool* threadpool,
	uint32_t last_command)
{
	uint32_t command = atomic_load_explicit(&threadpool->command, memory_order_relaxed);
	if (command != last_command) {
		atomic_thread_fence(memory_order_acquire);
		return command;
	}

	/* Spin-wait loop */
	for (uint32_t i = PTHREADPOOL_SPIN_WAIT_ITERATIONS; i != 0; i--) {
		/* This fence serves as a sleep instruction */
		atomic_thread_fence(memory_order_acquire);

		command = atomic_load_explicit(&threadpool->command, memory_order_relaxed);
		if (command != last_command) {
			atomic_thread_fence(memory_order_acquire);
			return command;
		}
	}

	/* Spin-wait timed out, fall back to mutex/futex wait */
	#if PTHREADPOOL_USE_FUTEX
		do {
			futex_wait(&threadpool->command, last_command);
			command = atomic_load_explicit(&threadpool->command, memory_order_relaxed);
		} while (command == last_command);
	#else
		/* Lock the command mutex */
		pthread_mutex_lock(&threadpool->command_mutex);
		/* Read the command */
		while ((command = atomic_load_explicit(&threadpool->command, memory_order_relaxed)) == last_command) {
			/* Wait for new command */
			pthread_cond_wait(&threadpool->command_condvar, &threadpool->command_mutex);
		}
		/* Read a new command */
		pthread_mutex_unlock(&threadpool->command_mutex);
	#endif
	atomic_thread_fence(memory_order_acquire);
	return command;
}

static void* thread_main(void* arg) {
	struct thread_info* thread = (struct thread_info*) arg;
	struct pthreadpool* threadpool = ((struct pthreadpool*) (thread - thread->thread_number)) - 1;
	uint32_t last_command = threadpool_command_init;
	struct fpu_state saved_fpu_state = { 0 };

	/* Check in */
	checkin_worker_thread(threadpool);

	/* Monitor new commands and act accordingly */
	for (;;) {
		uint32_t command = wait_for_new_command(threadpool, last_command);
		const uint32_t flags = atomic_load_explicit(&threadpool->flags, memory_order_relaxed);

		/* Process command */
		switch (command & THREADPOOL_COMMAND_MASK) {
			case threadpool_command_compute_1d:
			{
				if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
					saved_fpu_state = get_fpu_state();
					disable_fpu_denormals();
				}
				thread_parallelize_1d(threadpool, thread);
				if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
					set_fpu_state(saved_fpu_state);
				}
				break;
			}
			case threadpool_command_shutdown:
				/* Exit immediately: the master thread is waiting on pthread_join */
				return NULL;
			case threadpool_command_init:
				/* To inhibit compiler warning */
				break;
		}
		/* Notify the master thread that we finished processing */
		checkin_worker_thread(threadpool);
		/* Update last command */
		last_command = command;
	};
}

static struct pthreadpool* pthreadpool_allocate(size_t threads_count) {
	const size_t threadpool_size = sizeof(struct pthreadpool) + threads_count * sizeof(struct thread_info);
	struct pthreadpool* threadpool = NULL;
	#if defined(__ANDROID__)
		/*
		 * Android didn't get posix_memalign until API level 17 (Android 4.2).
		 * Use (otherwise obsolete) memalign function on Android platform.
		 */
		threadpool = memalign(PTHREADPOOL_CACHELINE_SIZE, threadpool_size);
		if (threadpool == NULL) {
			return NULL;
		}
	#else
		if (posix_memalign((void**) &threadpool, PTHREADPOOL_CACHELINE_SIZE, threadpool_size) != 0) {
			return NULL;
		}
	#endif
	memset(threadpool, 0, threadpool_size);
	return threadpool;
}

struct pthreadpool* pthreadpool_create(size_t threads_count) {
#if defined(__native_client__)
	pthread_once(&nacl_init_guard, nacl_init);
#endif

	if (threads_count == 0) {
		threads_count = (size_t) sysconf(_SC_NPROCESSORS_ONLN);
	}
	struct pthreadpool* threadpool = pthreadpool_allocate(threads_count);
	if (threadpool == NULL) {
		return NULL;
	}
	threadpool->threads_count = threads_count;
	for (size_t tid = 0; tid < threads_count; tid++) {
		threadpool->threads[tid].thread_number = tid;
	}

	/* Thread pool with a single thread computes everything on the caller thread. */
	if (threads_count > 1) {
		pthread_mutex_init(&threadpool->execution_mutex, NULL);
		#if !PTHREADPOOL_USE_FUTEX
			pthread_mutex_init(&threadpool->completion_mutex, NULL);
			pthread_cond_init(&threadpool->completion_condvar, NULL);
			pthread_mutex_init(&threadpool->command_mutex, NULL);
			pthread_cond_init(&threadpool->command_condvar, NULL);
		#endif

		#if PTHREADPOOL_USE_FUTEX
			atomic_store_explicit(&threadpool->has_active_threads, 1, memory_order_relaxed);
		#endif
		atomic_store_explicit(
			&threadpool->active_threads, threadpool->threads_count - 1 /* caller thread */, memory_order_release);

		/* Caller thread serves as worker #0. Thus, we create system threads starting with worker #1. */
		for (size_t tid = 1; tid < threads_count; tid++) {
			pthread_create(&threadpool->threads[tid].thread_object, NULL, &thread_main, &threadpool->threads[tid]);
		}

		/* Wait until all threads initialize */
		wait_worker_threads(threadpool);
	}
	return threadpool;
}

size_t pthreadpool_get_threads_count(struct pthreadpool* threadpool) {
	if (threadpool == NULL) {
		return 1;
	} else {
		return threadpool->threads_count;
	}
}

void pthreadpool_parallelize_1d(
	struct pthreadpool* threadpool,
	pthreadpool_task_1d_t task,
	void* argument,
	size_t range,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range; i++) {
			task(argument, i);
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Protect the global threadpool structures */
		pthread_mutex_lock(&threadpool->execution_mutex);

		#if !PTHREADPOOL_USE_FUTEX
			/* Lock the command variables to ensure that threads don't start processing before they observe complete command with all arguments */
			pthread_mutex_lock(&threadpool->command_mutex);
		#endif

		/* Setup global arguments */
		atomic_store_explicit(&threadpool->task, task, memory_order_relaxed);
		atomic_store_explicit(&threadpool->argument, argument, memory_order_relaxed);
		atomic_store_explicit(&threadpool->flags, flags, memory_order_relaxed);

		/* Locking of completion_mutex not needed: readers are sleeping on command_condvar */
		atomic_store_explicit(
			&threadpool->active_threads, threadpool->threads_count - 1 /* caller thread */, memory_order_relaxed);
		#if PTHREADPOOL_USE_FUTEX
			atomic_store_explicit(&threadpool->has_active_threads, 1, memory_order_relaxed);
		#endif

		/* Spread the work between threads */
		for (size_t tid = 0; tid < threadpool->threads_count; tid++) {
			struct thread_info* thread = &threadpool->threads[tid];
			const size_t range_start = multiply_divide(range, tid, threadpool->threads_count);
			const size_t range_end = multiply_divide(range, tid + 1, threadpool->threads_count);
			atomic_store_explicit(&thread->range_start, range_start, memory_order_relaxed);
			atomic_store_explicit(&thread->range_end, range_end, memory_order_relaxed);
			atomic_store_explicit(&thread->range_length, range_end - range_start, memory_order_relaxed);
		}

		#if PTHREADPOOL_USE_FUTEX
			/*
			 * Make new command parameters globally visible. Having this fence before updating the command is imporatnt: it
			 * guarantees that if a worker thread observes new command value, it also observes the updated command parameters.
			 */
			atomic_thread_fence(memory_order_release);
		#endif

		/*
		 * Update the threadpool command.
		 * Imporantly, do it after initializing command parameters (range, task, argument)
		 * ~(threadpool->command | THREADPOOL_COMMAND_MASK) flips the bits not in command mask
		 * to ensure the unmasked command is different then the last command, because worker threads
		 * monitor for change in the unmasked command.
		 */
		const uint32_t old_command = atomic_load_explicit(&threadpool->command, memory_order_relaxed);
		const uint32_t new_command = ~(old_command | THREADPOOL_COMMAND_MASK) | threadpool_command_compute_1d;

		#if PTHREADPOOL_USE_FUTEX
			atomic_store_explicit(&threadpool->command, new_command, memory_order_release);

			/* Wake up the threads */
			futex_wake_all(&threadpool->command);
		#else
			atomic_store_explicit(&threadpool->command, new_command, memory_order_relaxed);

			/* Unlock the command variables before waking up the threads for better performance */
			pthread_mutex_unlock(&threadpool->command_mutex);

			/* Wake up the threads */
			pthread_cond_broadcast(&threadpool->command_condvar);
		#endif

		/* Save and modify FPU denormals control, if needed */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}

		/* Do computations as worker #0 */
		thread_parallelize_1d(threadpool, &threadpool->threads[0]);

		/* Restore FPU denormals control, if needed */
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}

		/* Wait until the threads finish computation */
		wait_worker_threads(threadpool);

		/* Make changes by other threads visible to this thread */
		atomic_thread_fence(memory_order_acquire);

		/* Unprotect the global threadpool structures */
		pthread_mutex_unlock(&threadpool->execution_mutex);
	}
}

struct compute_1d_tile_1d_context {
	pthreadpool_task_1d_tile_1d_t task;
	void* argument;
	size_t range;
	size_t tile;
};

static void compute_1d_tile_1d(const struct compute_1d_tile_1d_context* context, size_t linear_index) {
	const size_t tile_index = linear_index;
	const size_t index = tile_index * context->tile;
	const size_t tile = min(context->tile, context->range - index);
	context->task(context->argument, index, tile);
}

void pthreadpool_parallelize_1d_tile_1d(
	pthreadpool_t threadpool,
	pthreadpool_task_1d_tile_1d_t task,
	void* argument,
	size_t range,
	size_t tile,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range; i += tile) {
			task(argument, i, min(range - i, tile));
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Execute in parallel on the thread pool using linearized index */
		const size_t tile_range = divide_round_up(range, tile);
		struct compute_1d_tile_1d_context context = {
			.task = task,
			.argument = argument,
			.range = range,
			.tile = tile
		};
		pthreadpool_parallelize_1d(threadpool, (pthreadpool_task_1d_t) compute_1d_tile_1d, &context, tile_range, flags);
	}
}

struct compute_2d_context {
	pthreadpool_task_2d_t task;
	void* argument;
	struct fxdiv_divisor_size_t range_j;
};

static void compute_2d(const struct compute_2d_context* context, size_t linear_index) {
	const struct fxdiv_divisor_size_t range_j = context->range_j;
	const struct fxdiv_result_size_t index = fxdiv_divide_size_t(linear_index, range_j);
	context->task(context->argument, index.quotient, index.remainder);
}

void pthreadpool_parallelize_2d(
	struct pthreadpool* threadpool,
	pthreadpool_task_2d_t task,
	void* argument,
	size_t range_i,
	size_t range_j,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range_i; i++) {
			for (size_t j = 0; j < range_j; j++) {
				task(argument, i, j);
			}
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Execute in parallel on the thread pool using linearized index */
		struct compute_2d_context context = {
			.task = task,
			.argument = argument,
			.range_j = fxdiv_init_size_t(range_j)
		};
		pthreadpool_parallelize_1d(threadpool, (pthreadpool_task_1d_t) compute_2d, &context, range_i * range_j, flags);
	}
}

struct compute_2d_tile_1d_context {
	pthreadpool_task_2d_tile_1d_t task;
	void* argument;
	struct fxdiv_divisor_size_t tile_range_j;
	size_t range_i;
	size_t range_j;
	size_t tile_j;
};

static void compute_2d_tile_1d(const struct compute_2d_tile_1d_context* context, size_t linear_index) {
	const struct fxdiv_divisor_size_t tile_range_j = context->tile_range_j;
	const struct fxdiv_result_size_t tile_index = fxdiv_divide_size_t(linear_index, tile_range_j);
	const size_t max_tile_j = context->tile_j;
	const size_t index_i = tile_index.quotient;
	const size_t index_j = tile_index.remainder * max_tile_j;
	const size_t tile_j = min(max_tile_j, context->range_j - index_j);
	context->task(context->argument, index_i, index_j, tile_j);
}

void pthreadpool_parallelize_2d_tile_1d(
	pthreadpool_t threadpool,
	pthreadpool_task_2d_tile_1d_t task,
	void* argument,
	size_t range_i,
	size_t range_j,
	size_t tile_j,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range_i; i++) {
			for (size_t j = 0; j < range_j; j += tile_j) {
				task(argument, i, j, min(range_j - j, tile_j));
			}
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Execute in parallel on the thread pool using linearized index */
		const size_t tile_range_j = divide_round_up(range_j, tile_j);
		struct compute_2d_tile_1d_context context = {
			.task = task,
			.argument = argument,
			.tile_range_j = fxdiv_init_size_t(tile_range_j),
			.range_i = range_i,
			.range_j = range_j,
			.tile_j = tile_j
		};
		pthreadpool_parallelize_1d(threadpool, (pthreadpool_task_1d_t) compute_2d_tile_1d, &context, range_i * tile_range_j, flags);
	}
}

struct compute_2d_tile_2d_context {
	pthreadpool_task_2d_tile_2d_t task;
	void* argument;
	struct fxdiv_divisor_size_t tile_range_j;
	size_t range_i;
	size_t range_j;
	size_t tile_i;
	size_t tile_j;
};

static void compute_2d_tile_2d(const struct compute_2d_tile_2d_context* context, size_t linear_index) {
	const struct fxdiv_divisor_size_t tile_range_j = context->tile_range_j;
	const struct fxdiv_result_size_t tile_index = fxdiv_divide_size_t(linear_index, tile_range_j);
	const size_t max_tile_i = context->tile_i;
	const size_t max_tile_j = context->tile_j;
	const size_t index_i = tile_index.quotient * max_tile_i;
	const size_t index_j = tile_index.remainder * max_tile_j;
	const size_t tile_i = min(max_tile_i, context->range_i - index_i);
	const size_t tile_j = min(max_tile_j, context->range_j - index_j);
	context->task(context->argument, index_i, index_j, tile_i, tile_j);
}

void pthreadpool_parallelize_2d_tile_2d(
	pthreadpool_t threadpool,
	pthreadpool_task_2d_tile_2d_t task,
	void* argument,
	size_t range_i,
	size_t range_j,
	size_t tile_i,
	size_t tile_j,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range_i; i += tile_i) {
			for (size_t j = 0; j < range_j; j += tile_j) {
				task(argument, i, j, min(range_i - i, tile_i), min(range_j - j, tile_j));
			}
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Execute in parallel on the thread pool using linearized index */
		const size_t tile_range_i = divide_round_up(range_i, tile_i);
		const size_t tile_range_j = divide_round_up(range_j, tile_j);
		struct compute_2d_tile_2d_context context = {
			.task = task,
			.argument = argument,
			.tile_range_j = fxdiv_init_size_t(tile_range_j),
			.range_i = range_i,
			.range_j = range_j,
			.tile_i = tile_i,
			.tile_j = tile_j
		};
		pthreadpool_parallelize_1d(threadpool, (pthreadpool_task_1d_t) compute_2d_tile_2d, &context, tile_range_i * tile_range_j, flags);
	}
}

struct compute_3d_tile_2d_context {
	pthreadpool_task_3d_tile_2d_t task;
	void* argument;
	struct fxdiv_divisor_size_t tile_range_j;
	struct fxdiv_divisor_size_t tile_range_k;
	size_t range_j;
	size_t range_k;
	size_t tile_j;
	size_t tile_k;
};

static void compute_3d_tile_2d(const struct compute_3d_tile_2d_context* context, size_t linear_index) {
	const struct fxdiv_divisor_size_t tile_range_k = context->tile_range_k;
	const struct fxdiv_result_size_t tile_index_ij_k = fxdiv_divide_size_t(linear_index, tile_range_k);
	const struct fxdiv_divisor_size_t tile_range_j = context->tile_range_j;
	const struct fxdiv_result_size_t tile_index_i_j = fxdiv_divide_size_t(tile_index_ij_k.quotient, tile_range_j);
	const size_t max_tile_j = context->tile_j;
	const size_t max_tile_k = context->tile_k;
	const size_t index_i = tile_index_i_j.quotient;
	const size_t index_j = tile_index_i_j.remainder * max_tile_j;
	const size_t index_k = tile_index_ij_k.remainder * max_tile_k;
	const size_t tile_j = min(max_tile_j, context->range_j - index_j);
	const size_t tile_k = min(max_tile_k, context->range_k - index_k);
	context->task(context->argument, index_i, index_j, index_k, tile_j, tile_k);
}

void pthreadpool_parallelize_3d_tile_2d(
	pthreadpool_t threadpool,
	pthreadpool_task_3d_tile_2d_t task,
	void* argument,
	size_t range_i,
	size_t range_j,
	size_t range_k,
	size_t tile_j,
	size_t tile_k,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range_i; i++) {
			for (size_t j = 0; j < range_j; j += tile_j) {
				for (size_t k = 0; k < range_k; k += tile_k) {
					task(argument, i, j, k, min(range_j - j, tile_j), min(range_k - k, tile_k));
				}
			}
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Execute in parallel on the thread pool using linearized index */
		const size_t tile_range_j = divide_round_up(range_j, tile_j);
		const size_t tile_range_k = divide_round_up(range_k, tile_k);
		struct compute_3d_tile_2d_context context = {
			.task = task,
			.argument = argument,
			.tile_range_j = fxdiv_init_size_t(tile_range_j),
			.tile_range_k = fxdiv_init_size_t(tile_range_k),
			.range_j = range_j,
			.range_k = range_k,
			.tile_j = tile_j,
			.tile_k = tile_k
		};
		pthreadpool_parallelize_1d(threadpool,
			(pthreadpool_task_1d_t) compute_3d_tile_2d, &context,
			range_i * tile_range_j * tile_range_k, flags);
	}
}

struct compute_4d_tile_2d_context {
	pthreadpool_task_4d_tile_2d_t task;
	void* argument;
	struct fxdiv_divisor_size_t tile_range_kl;
	struct fxdiv_divisor_size_t range_j;
	struct fxdiv_divisor_size_t tile_range_l;
	size_t range_k;
	size_t range_l;
	size_t tile_k;
	size_t tile_l;
};

static void compute_4d_tile_2d(const struct compute_4d_tile_2d_context* context, size_t linear_index) {
	const struct fxdiv_divisor_size_t tile_range_kl = context->tile_range_kl;
	const struct fxdiv_result_size_t tile_index_ij_kl = fxdiv_divide_size_t(linear_index, tile_range_kl);
	const struct fxdiv_divisor_size_t range_j = context->range_j;
	const struct fxdiv_result_size_t tile_index_i_j = fxdiv_divide_size_t(tile_index_ij_kl.quotient, range_j);
	const struct fxdiv_divisor_size_t tile_range_l = context->tile_range_l;
	const struct fxdiv_result_size_t tile_index_k_l = fxdiv_divide_size_t(tile_index_ij_kl.remainder, tile_range_l);
	const size_t max_tile_k = context->tile_k;
	const size_t max_tile_l = context->tile_l;
	const size_t index_i = tile_index_i_j.quotient;
	const size_t index_j = tile_index_i_j.remainder;
	const size_t index_k = tile_index_k_l.quotient * max_tile_k;
	const size_t index_l = tile_index_k_l.remainder * max_tile_l;
	const size_t tile_k = min(max_tile_k, context->range_k - index_k);
	const size_t tile_l = min(max_tile_l, context->range_l - index_l);
	context->task(context->argument, index_i, index_j, index_k, index_l, tile_k, tile_l);
}

void pthreadpool_parallelize_4d_tile_2d(
	pthreadpool_t threadpool,
	pthreadpool_task_4d_tile_2d_t task,
	void* argument,
	size_t range_i,
	size_t range_j,
	size_t range_k,
	size_t range_l,
	size_t tile_k,
	size_t tile_l,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range_i; i++) {
			for (size_t j = 0; j < range_j; j++) {
				for (size_t k = 0; k < range_k; k += tile_k) {
					for (size_t l = 0; l < range_l; l += tile_l) {
						task(argument, i, j, k, l,
							min(range_k - k, tile_k), min(range_l - l, tile_l));
					}
				}
			}
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Execute in parallel on the thread pool using linearized index */
		const size_t tile_range_k = divide_round_up(range_k, tile_k);
		const size_t tile_range_l = divide_round_up(range_l, tile_l);
		struct compute_4d_tile_2d_context context = {
			.task = task,
			.argument = argument,
			.tile_range_kl = fxdiv_init_size_t(tile_range_k * tile_range_l),
			.range_j = fxdiv_init_size_t(range_j),
			.tile_range_l = fxdiv_init_size_t(tile_range_l),
			.range_k = range_k,
			.range_l = range_l,
			.tile_k = tile_k,
			.tile_l = tile_l
		};
		pthreadpool_parallelize_1d(threadpool,
			(pthreadpool_task_1d_t) compute_4d_tile_2d, &context,
			range_i * range_j * tile_range_k * tile_range_l, flags);
	}
}

struct compute_5d_tile_2d_context {
	pthreadpool_task_5d_tile_2d_t task;
	void* argument;
	struct fxdiv_divisor_size_t tile_range_lm;
	struct fxdiv_divisor_size_t range_k;
	struct fxdiv_divisor_size_t tile_range_m;
	struct fxdiv_divisor_size_t range_j;
	size_t range_l;
	size_t range_m;
	size_t tile_l;
	size_t tile_m;
};

static void compute_5d_tile_2d(const struct compute_5d_tile_2d_context* context, size_t linear_index) {
	const struct fxdiv_divisor_size_t tile_range_lm = context->tile_range_lm;
	const struct fxdiv_result_size_t tile_index_ijk_lm = fxdiv_divide_size_t(linear_index, tile_range_lm);
	const struct fxdiv_divisor_size_t range_k = context->range_k;
	const struct fxdiv_result_size_t tile_index_ij_k = fxdiv_divide_size_t(tile_index_ijk_lm.quotient, range_k);
	const struct fxdiv_divisor_size_t tile_range_m = context->tile_range_m;
	const struct fxdiv_result_size_t tile_index_l_m = fxdiv_divide_size_t(tile_index_ijk_lm.remainder, tile_range_m);
	const struct fxdiv_divisor_size_t range_j = context->range_j;
	const struct fxdiv_result_size_t tile_index_i_j = fxdiv_divide_size_t(tile_index_ij_k.quotient, range_j);

	const size_t max_tile_l = context->tile_l;
	const size_t max_tile_m = context->tile_m;
	const size_t index_i = tile_index_i_j.quotient;
	const size_t index_j = tile_index_i_j.remainder;
	const size_t index_k = tile_index_ij_k.remainder;
	const size_t index_l = tile_index_l_m.quotient * max_tile_l;
	const size_t index_m = tile_index_l_m.remainder * max_tile_m;
	const size_t tile_l = min(max_tile_l, context->range_l - index_l);
	const size_t tile_m = min(max_tile_m, context->range_m - index_m);
	context->task(context->argument, index_i, index_j, index_k, index_l, index_m, tile_l, tile_m);
}

void pthreadpool_parallelize_5d_tile_2d(
	pthreadpool_t threadpool,
	pthreadpool_task_5d_tile_2d_t task,
	void* argument,
	size_t range_i,
	size_t range_j,
	size_t range_k,
	size_t range_l,
	size_t range_m,
	size_t tile_l,
	size_t tile_m,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range_i; i++) {
			for (size_t j = 0; j < range_j; j++) {
				for (size_t k = 0; k < range_k; k++) {
					for (size_t l = 0; l < range_l; l += tile_l) {
						for (size_t m = 0; m < range_m; m += tile_m) {
							task(argument, i, j, k, l, m,
								min(range_l - l, tile_l), min(range_m - m, tile_m));
						}
					}
				}
			}
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Execute in parallel on the thread pool using linearized index */
		const size_t tile_range_l = divide_round_up(range_l, tile_l);
		const size_t tile_range_m = divide_round_up(range_m, tile_m);
		struct compute_5d_tile_2d_context context = {
			.task = task,
			.argument = argument,
			.tile_range_lm = fxdiv_init_size_t(tile_range_l * tile_range_m),
			.range_k = fxdiv_init_size_t(range_k),
			.tile_range_m = fxdiv_init_size_t(tile_range_m),
			.range_j = fxdiv_init_size_t(range_j),
			.range_l = range_l,
			.range_m = range_m,
			.tile_l = tile_l,
			.tile_m = tile_m,
		};
		pthreadpool_parallelize_1d(threadpool,
			(pthreadpool_task_1d_t) compute_5d_tile_2d, &context,
			range_i * range_j * range_k * tile_range_l * tile_range_m, flags);
	}
}

struct compute_6d_tile_2d_context {
	pthreadpool_task_6d_tile_2d_t task;
	void* argument;
	struct fxdiv_divisor_size_t tile_range_lmn;
	struct fxdiv_divisor_size_t range_k;
	struct fxdiv_divisor_size_t tile_range_n;
	struct fxdiv_divisor_size_t range_j;
	struct fxdiv_divisor_size_t tile_range_m;
	size_t range_m;
	size_t range_n;
	size_t tile_m;
	size_t tile_n;
};

static void compute_6d_tile_2d(const struct compute_6d_tile_2d_context* context, size_t linear_index) {
	const struct fxdiv_divisor_size_t tile_range_lmn = context->tile_range_lmn;
	const struct fxdiv_result_size_t tile_index_ijk_lmn = fxdiv_divide_size_t(linear_index, tile_range_lmn);
	const struct fxdiv_divisor_size_t range_k = context->range_k;
	const struct fxdiv_result_size_t tile_index_ij_k = fxdiv_divide_size_t(tile_index_ijk_lmn.quotient, range_k);
	const struct fxdiv_divisor_size_t tile_range_n = context->tile_range_n;
	const struct fxdiv_result_size_t tile_index_lm_n = fxdiv_divide_size_t(tile_index_ijk_lmn.remainder, tile_range_n);
	const struct fxdiv_divisor_size_t range_j = context->range_j;
	const struct fxdiv_result_size_t tile_index_i_j = fxdiv_divide_size_t(tile_index_ij_k.quotient, range_j);
	const struct fxdiv_divisor_size_t tile_range_m = context->tile_range_m;
	const struct fxdiv_result_size_t tile_index_l_m = fxdiv_divide_size_t(tile_index_lm_n.quotient, tile_range_m);

	const size_t max_tile_m = context->tile_m;
	const size_t max_tile_n = context->tile_n;
	const size_t index_i = tile_index_i_j.quotient;
	const size_t index_j = tile_index_i_j.remainder;
	const size_t index_k = tile_index_ij_k.remainder;
	const size_t index_l = tile_index_l_m.quotient;
	const size_t index_m = tile_index_l_m.remainder * max_tile_m;
	const size_t index_n = tile_index_lm_n.remainder * max_tile_n;
	const size_t tile_m = min(max_tile_m, context->range_m - index_m);
	const size_t tile_n = min(max_tile_n, context->range_n - index_n);
	context->task(context->argument, index_i, index_j, index_k, index_l, index_m, index_n, tile_m, tile_n);
}

void pthreadpool_parallelize_6d_tile_2d(
	pthreadpool_t threadpool,
	pthreadpool_task_6d_tile_2d_t task,
	void* argument,
	size_t range_i,
	size_t range_j,
	size_t range_k,
	size_t range_l,
	size_t range_m,
	size_t range_n,
	size_t tile_m,
	size_t tile_n,
	uint32_t flags)
{
	if (threadpool == NULL || threadpool->threads_count <= 1) {
		/* No thread pool used: execute task sequentially on the calling thread */
		struct fpu_state saved_fpu_state = { 0 };
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			saved_fpu_state = get_fpu_state();
			disable_fpu_denormals();
		}
		for (size_t i = 0; i < range_i; i++) {
			for (size_t j = 0; j < range_j; j++) {
				for (size_t k = 0; k < range_k; k++) {
					for (size_t l = 0; l < range_l; l++) {
						for (size_t m = 0; m < range_m; m += tile_m) {
							for (size_t n = 0; n < range_n; n += tile_n) {
								task(argument, i, j, k, l, m, n,
									min(range_m - m, tile_m), min(range_n - n, tile_n));
							}
						}
					}
				}
			}
		}
		if (flags & PTHREADPOOL_FLAG_DISABLE_DENORMALS) {
			set_fpu_state(saved_fpu_state);
		}
	} else {
		/* Execute in parallel on the thread pool using linearized index */
		const size_t tile_range_m = divide_round_up(range_m, tile_m);
		const size_t tile_range_n = divide_round_up(range_n, tile_n);
		struct compute_6d_tile_2d_context context = {
			.task = task,
			.argument = argument,
			.tile_range_lmn = fxdiv_init_size_t(range_l * tile_range_m * tile_range_n),
			.range_k = fxdiv_init_size_t(range_k),
			.tile_range_n = fxdiv_init_size_t(tile_range_n),
			.range_j = fxdiv_init_size_t(range_j),
			.tile_range_m = fxdiv_init_size_t(tile_range_m),
			.range_m = range_m,
			.range_n = range_n,
			.tile_m = tile_m,
			.tile_n = tile_n,
		};
		pthreadpool_parallelize_1d(threadpool,
			(pthreadpool_task_1d_t) compute_6d_tile_2d, &context,
			range_i * range_j * range_k * range_l * tile_range_m * tile_range_n, flags);
	}
}

void pthreadpool_destroy(struct pthreadpool* threadpool) {
	if (threadpool != NULL) {
		if (threadpool->threads_count > 1) {
			#if PTHREADPOOL_USE_FUTEX
				atomic_store_explicit(
					&threadpool->active_threads, threadpool->threads_count - 1 /* caller thread */, memory_order_relaxed);
				atomic_store_explicit(&threadpool->has_active_threads, 1, memory_order_release);

				atomic_store_explicit(&threadpool->command, threadpool_command_shutdown, memory_order_release);

				/* Wake up worker threads */
				futex_wake_all(&threadpool->command);
			#else
				/* Lock the command variable to ensure that threads don't shutdown until both command and active_threads are updated */
				pthread_mutex_lock(&threadpool->command_mutex);

				/* Locking of completion_mutex not needed: readers are sleeping on command_condvar */
				atomic_store_explicit(
					&threadpool->active_threads, threadpool->threads_count - 1 /* caller thread */, memory_order_release);

				/* Update the threadpool command. */
				atomic_store_explicit(&threadpool->command, threadpool_command_shutdown, memory_order_release);

				/* Wake up worker threads */
				pthread_cond_broadcast(&threadpool->command_condvar);

				/* Commit the state changes and let workers start processing */
				pthread_mutex_unlock(&threadpool->command_mutex);
			#endif

			/* Wait until all threads return */
			for (size_t thread = 1; thread < threadpool->threads_count; thread++) {
				pthread_join(threadpool->threads[thread].thread_object, NULL);
			}

			/* Release resources */
			pthread_mutex_destroy(&threadpool->execution_mutex);
			#if !PTHREADPOOL_USE_FUTEX
				pthread_mutex_destroy(&threadpool->completion_mutex);
				pthread_cond_destroy(&threadpool->completion_condvar);
				pthread_mutex_destroy(&threadpool->command_mutex);
				pthread_cond_destroy(&threadpool->command_condvar);
			#endif
		}
		free(threadpool);
	}
}