From dc02f09809ee3d7b3e7a1eeabb2828bc06f91f32 Mon Sep 17 00:00:00 2001 From: Dongwoo Lee Date: Tue, 7 Feb 2023 08:50:33 -0800 Subject: [PATCH] util: thread: Prevent to run thread before creation finished Currently thread can be terminated before creation process is over, and it can either cause wrong memory access on thread context. To prevent this situation, thread lock is acquired before creating thread, and thus the new thread cannot acquire lock and is suspended until lock is released after creation is over. Change-Id: Ic769c4dfa522e115959cf25c2c0c78779d176743 Signed-off-by: Dongwoo Lee --- src/util/thread.c | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/util/thread.c b/src/util/thread.c index 0bf45ec..f6201f1 100644 --- a/src/util/thread.c +++ b/src/util/thread.c @@ -28,11 +28,14 @@ static void __thread_loop_main(void *_ctx) struct thread_context *ctx = _ctx; void *result; + mtx_lock(&ctx->lock); while (ctx->state != THREAD_STATE_TERMINATED) { - if (ctx->timer.tv_sec || ctx->timer.tv_nsec) + if (ctx->timer.tv_sec || ctx->timer.tv_nsec) { + mtx_unlock(&ctx->lock); thrd_sleep(&ctx->timer, NULL); + mtx_lock(&ctx->lock); + } - mtx_lock(&ctx->lock); while (ctx->state == THREAD_STATE_STOPPED) cnd_wait(&ctx->wait, &ctx->lock); if (ctx->state == THREAD_STATE_TERMINATED) @@ -46,8 +49,8 @@ static void __thread_loop_main(void *_ctx) ctx->state = THREAD_STATE_TERMINATED; ctx->result = result; } - mtx_unlock(&ctx->lock); } + mtx_unlock(&ctx->lock); thrd_exit(ret); } @@ -106,6 +109,7 @@ static int do_create_thread(struct thread **thread, ctx->func = func; ctx->arg = arg; + mtx_lock(&ctx->lock); switch (type) { case THREAD_TYPE_WORKER: ctx->state = THREAD_STATE_STOPPED; @@ -135,10 +139,12 @@ static int do_create_thread(struct thread **thread, new_thread->ctx = ctx; *thread = new_thread; + mtx_unlock(&ctx->lock); return 0; err: + mtx_unlock(&ctx->lock); cnd_destroy(&ctx->wait); mtx_destroy(&ctx->lock); free(ctx); -- 2.34.1