1 /* Standard C headers */
2 #include <assert.h>
3 #include <stddef.h>
4 #include <stdlib.h>
5 #include <string.h>
6 
7 /* POSIX headers */
8 #ifdef __ANDROID__
9 	#include <malloc.h>
10 #endif
11 
12 /* Windows headers */
13 #ifdef _WIN32
14 	#include <malloc.h>
15 #endif
16 
17 /* Internal library headers */
18 #include "threadpool-common.h"
19 #include "threadpool-object.h"
20 
21 
pthreadpool_allocate(size_t threads_count)22 PTHREADPOOL_INTERNAL struct pthreadpool* pthreadpool_allocate(
23 	size_t threads_count)
24 {
25 	assert(threads_count >= 1);
26 
27 	const size_t threadpool_size = sizeof(struct pthreadpool) + threads_count * sizeof(struct thread_info);
28 	struct pthreadpool* threadpool = NULL;
29 	#if defined(__ANDROID__)
30 		/*
31 		 * Android didn't get posix_memalign until API level 17 (Android 4.2).
32 		 * Use (otherwise obsolete) memalign function on Android platform.
33 		 */
34 		threadpool = memalign(PTHREADPOOL_CACHELINE_SIZE, threadpool_size);
35 		if (threadpool == NULL) {
36 			return NULL;
37 		}
38 	#elif defined(_WIN32)
39 		threadpool = _aligned_malloc(threadpool_size, PTHREADPOOL_CACHELINE_SIZE);
40 		if (threadpool == NULL) {
41 			return NULL;
42 		}
43 	#else
44 		if (posix_memalign((void**) &threadpool, PTHREADPOOL_CACHELINE_SIZE, threadpool_size) != 0) {
45 			return NULL;
46 		}
47 	#endif
48 	memset(threadpool, 0, threadpool_size);
49 	return threadpool;
50 }
51 
52 
pthreadpool_deallocate(struct pthreadpool * threadpool)53 PTHREADPOOL_INTERNAL void pthreadpool_deallocate(
54 	struct pthreadpool* threadpool)
55 {
56 	assert(threadpool != NULL);
57 
58 	const size_t threadpool_size = sizeof(struct pthreadpool) + threadpool->threads_count.value * sizeof(struct thread_info);
59 	memset(threadpool, 0, threadpool_size);
60 
61 	#ifdef _WIN32
62 		_aligned_free(threadpool);
63 	#else
64 		free(threadpool);
65 	#endif
66 }
67