aboutsummaryrefslogtreecommitdiff
path: root/src/memory.c
diff options
context:
space:
mode:
authorMarat Dukhan <maratek@google.com>2020-04-01 17:08:30 -0700
committerMarat Dukhan <maratek@google.com>2020-04-01 17:08:30 -0700
commitfc793bc6d7eab64756df79971556594bf4ab145b (patch)
tree669f93c06ca276279aa3acb6b91edb8029e5f5a7 /src/memory.c
parent5b41aa6060588e26fd25ace6dc4afccfd4793997 (diff)
downloadpthreadpool-fc793bc6d7eab64756df79971556594bf4ab145b.tar.gz
Refactor pthreadpool implementation
Split implementation into two types of components: - Components dependent on threading API - Portable components
Diffstat (limited to 'src/memory.c')
-rw-r--r--src/memory.c67
1 files changed, 67 insertions, 0 deletions
diff --git a/src/memory.c b/src/memory.c
new file mode 100644
index 0000000..020cb6d
--- /dev/null
+++ b/src/memory.c
@@ -0,0 +1,67 @@
+/* Standard C headers */
+#include <assert.h>
+#include <stddef.h>
+#include <stdlib.h>
+#include <string.h>
+
+/* POSIX headers */
+#ifdef __ANDROID__
+ #include <malloc.h>
+#endif
+
+/* Windows headers */
+#ifdef _WIN32
+ #define NOMINMAX
+ #include <malloc.h>
+#endif
+
+/* Internal headers */
+#include "threadpool-common.h"
+#include "threadpool-object.h"
+
+
+PTHREADPOOL_INTERNAL struct pthreadpool* pthreadpool_allocate(
+ size_t threads_count)
+{
+ assert(threads_count >= 1);
+
+ 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;
+ }
+ #elif defined(_WIN32)
+ threadpool = _aligned_malloc(threadpool_size, PTHREADPOOL_CACHELINE_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;
+}
+
+
+PTHREADPOOL_INTERNAL void pthreadpool_deallocate(
+ struct pthreadpool* threadpool)
+{
+ assert(threadpool != NULL);
+
+ const size_t threadpool_size = sizeof(struct pthreadpool) + threadpool->threads_count * sizeof(struct thread_info);
+ memset(threadpool, 0, threadpool_size);
+
+ #ifdef _WIN32
+ _aligned_free(threadpool);
+ #else
+ free(threadpool);
+ #endif
+}