From 48cdf1a9d6e687abe71421c3cce59b93ab34ac54 Mon Sep 17 00:00:00 2001 From: Quentin Young Date: Wed, 17 May 2017 17:11:34 +0000 Subject: [PATCH] lib: enforce thread_cancel() MT-unsafe invariant Signed-off-by: Quentin Young --- lib/thread.c | 9 ++++++--- lib/thread.h | 1 + 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/thread.c b/lib/thread.c index 2843a9211..ccb635a87 100644 --- a/lib/thread.c +++ b/lib/thread.c @@ -377,6 +377,7 @@ thread_master_create (void) rv->timer->update = rv->background->update = thread_timer_update; rv->spin = true; rv->handle_signals = true; + rv->owner = pthread_self(); #if defined(HAVE_POLL_CALL) rv->handler.pfdsize = rv->fd_limit; @@ -1021,7 +1022,7 @@ thread_cancel_read_or_write (struct thread *thread, short int state) * Cancel thread from scheduler. * * This function is *NOT* MT-safe. DO NOT call it from any other pthread except - * the one which owns thread->master. + * the one which owns thread->master. You will crash. */ void thread_cancel (struct thread *thread) @@ -1030,8 +1031,10 @@ thread_cancel (struct thread *thread) struct pqueue *queue = NULL; struct thread **thread_array = NULL; - pthread_mutex_lock (&thread->master->mtx); pthread_mutex_lock (&thread->mtx); + pthread_mutex_lock (&thread->master->mtx); + + assert (pthread_self() == thread->master->owner); switch (thread->type) { @@ -1092,8 +1095,8 @@ thread_cancel (struct thread *thread) thread_add_unuse (thread->master, thread); done: - pthread_mutex_unlock (&thread->mtx); pthread_mutex_unlock (&thread->master->mtx); + pthread_mutex_unlock (&thread->mtx); } /* Delete all events which has argument value arg. */ diff --git a/lib/thread.h b/lib/thread.h index 218672c7b..7e79eb38d 100644 --- a/lib/thread.h +++ b/lib/thread.h @@ -88,6 +88,7 @@ struct thread_master bool spin; bool handle_signals; pthread_mutex_t mtx; + pthread_t owner; }; typedef unsigned char thread_type; -- 2.39.5