util: thread: Prevent to run thread before creation finished 18/287918/4 accepted/tizen/unified/20230221.031435
authorDongwoo Lee <dwoo08.lee@samsung.com>
Tue, 7 Feb 2023 16:50:33 +0000 (08:50 -0800)
committerDongwoo Lee <dwoo08.lee@samsung.com>
Wed, 8 Feb 2023 06:03:59 +0000 (15:03 +0900)
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 <dwoo08.lee@samsung.com>
src/util/thread.c

index 0bf45ec..f6201f1 100644 (file)
@@ -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);