summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/common.c16
-rw-r--r--src/dbg.c18
2 files changed, 34 insertions, 0 deletions
diff --git a/src/common.c b/src/common.c
index bde1bac..f9e46d5 100644
--- a/src/common.c
+++ b/src/common.c
@@ -6,6 +6,9 @@
#include <stdlib.h>
#endif
+#ifdef USE_THREAD
+#include <pthread.h>
+#endif
// Initializes a new tinyff context.
ff_ctx* ff_init(ff_allocator* allocator)
@@ -27,12 +30,25 @@ ff_ctx* ff_init(ff_allocator* allocator)
ctx->allocator = *allocator;
+#ifdef USE_THREAD
+ /* initialize mutex used to protect ctx state */
+ if (pthread_mutex_init(&ctx->ff_lock, NULL) != 0) {
+ ctx->allocator.ff_free(ctx);
+ return NULL;
+ }
+#endif
+
return ctx;
}
void ff_cleanup(ff_ctx *ctx) {
if (!ctx) return;
ff_dprintf(ctx, "goodbye from tinyff ;]\n");
+
+#ifdef USE_THREAD
+ pthread_mutex_destroy(&ctx->ff_lock);
+#endif
+
ctx->allocator.ff_free(ctx);
}
diff --git a/src/dbg.c b/src/dbg.c
index a12545d..13c3f18 100644
--- a/src/dbg.c
+++ b/src/dbg.c
@@ -3,6 +3,10 @@
#include <stdarg.h>
#include <stdint.h>
+#ifdef USE_THREAD
+#include <pthread.h>
+#endif
+
static size_t ff_internal_itoa(int value, char* buf)
{
char temp[12];
@@ -52,6 +56,9 @@ static inline void ff_debug_flush(ff_ctx* ctx, char* buffer, size_t* idx)
{
if (*idx == 0) return;
+#ifdef USE_THREAD
+ pthread_mutex_lock(&ctx->ff_lock);
+#endif
ctx->ff_debug_stream.write(
buffer,
*idx,
@@ -59,6 +66,9 @@ static inline void ff_debug_flush(ff_ctx* ctx, char* buffer, size_t* idx)
);
*idx = 0;
+#ifdef USE_THREAD
+ pthread_mutex_unlock(&ctx->ff_lock);
+#endif
}
ff_result ff_dprintf(ff_ctx* ctx, const char *format, ...)
@@ -74,6 +84,10 @@ ff_result ff_dprintf(ff_ctx* ctx, const char *format, ...)
size_t buf_idx = 0;
const char* p = format;
+#ifdef USE_THREAD
+ pthread_mutex_lock(&ctx->ff_lock);
+#endif
+
while (*p) {
if (buf_idx >= sizeof(buffer) - 64) {
@@ -152,6 +166,10 @@ ff_result ff_dprintf(ff_ctx* ctx, const char *format, ...)
ff_debug_flush(ctx, buffer, &buf_idx);
+#ifdef USE_THREAD
+ pthread_mutex_unlock(&ctx->ff_lock);
+#endif
+
va_end(args);
return FF_RESULT_OK;
} \ No newline at end of file