diff --git a/src/gba/gba-thread.c b/src/gba/gba-thread.c index 027da1c9d..951cb22bb 100644 --- a/src/gba/gba-thread.c +++ b/src/gba/gba-thread.c @@ -7,7 +7,16 @@ #include #include +static pthread_key_t contextKey; + +static void createTLS(void) { + pthread_key_create(&contextKey, 0); +} + static void* _GBAThreadRun(void* context) { + static pthread_once_t once = PTHREAD_ONCE_INIT; + pthread_once(&once, createTLS); + struct ARMDebugger debugger; struct GBA gba; struct GBAThread* threadContext = context; @@ -18,11 +27,12 @@ static void* _GBAThreadRun(void* context) { pthread_sigmask(SIG_UNBLOCK, &signals, 0); GBAInit(&gba); + threadContext->gba = &gba; + pthread_setspecific(contextKey, threadContext); if (threadContext->renderer) { GBAVideoAssociateRenderer(&gba.video, threadContext->renderer); } - threadContext->gba = &gba; if (threadContext->fd >= 0) { if (threadContext->fname) { char* dotPoint = strrchr(threadContext->fname, '.'); @@ -100,3 +110,7 @@ void GBAThreadJoin(struct GBAThread* threadContext) { pthread_mutex_destroy(&threadContext->mutex); pthread_cond_destroy(&threadContext->cond); } + +struct GBAThread* GBAThreadGetContext(void) { + return pthread_getspecific(contextKey); +} diff --git a/src/gba/gba-thread.h b/src/gba/gba-thread.h index df2877ce2..ea00d465c 100644 --- a/src/gba/gba-thread.h +++ b/src/gba/gba-thread.h @@ -24,5 +24,6 @@ struct GBAThread { int GBAThreadStart(struct GBAThread* threadContext); void GBAThreadJoin(struct GBAThread* threadContext); +struct GBAThread* GBAThreadGetContext(void); #endif diff --git a/src/gba/gba.c b/src/gba/gba.c index aaadcfa7d..4c9e49fa4 100644 --- a/src/gba/gba.c +++ b/src/gba/gba.c @@ -2,6 +2,7 @@ #include "gba-bios.h" #include "gba-io.h" +#include "gba-thread.h" #include "debugger.h" @@ -368,6 +369,12 @@ int GBAHalt(struct GBA* gba) { } void GBALog(struct GBA* gba, enum GBALogLevel level, const char* format, ...) { + if (!gba) { + struct GBAThread* threadContext = GBAThreadGetContext(); + if (threadContext) { + gba = threadContext->gba; + } + } if (gba && level < gba->logLevel) { return; }