|
|
@@ -21,15 +21,23 @@ platform_thread_t *platform_thread_init( const char *name,
|
|
|
|
|
|
thread_entry = (void *(*)(void*))entry;
|
|
|
thread = platform_memory_alloc(sizeof(platform_thread_t));
|
|
|
-
|
|
|
- res = pthread_create(&thread->thread, NULL, thread_entry, param);
|
|
|
- if(res != 0) {
|
|
|
- platform_memory_free(thread);
|
|
|
+
|
|
|
+ if (NULL == thread) {
|
|
|
+ return NULL;
|
|
|
}
|
|
|
|
|
|
+ // 修复竞态条件:在创建线程之前先初始化 mutex 和 cond
|
|
|
+ // 否则新线程可能在这些成员初始化之前就开始访问它们
|
|
|
thread->mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
|
|
|
thread->cond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;
|
|
|
|
|
|
+ // 现在才创建线程,此时 mutex 和 cond 已经初始化完成
|
|
|
+ res = pthread_create(&thread->thread, NULL, thread_entry, param);
|
|
|
+ if(res != 0) {
|
|
|
+ platform_memory_free(thread);
|
|
|
+ return NULL;
|
|
|
+ }
|
|
|
+
|
|
|
return thread;
|
|
|
}
|
|
|
|
|
|
@@ -40,6 +48,10 @@ void platform_thread_startup(platform_thread_t* thread)
|
|
|
|
|
|
void platform_thread_stop(platform_thread_t* thread)
|
|
|
{
|
|
|
+ // 添加 NULL 检查,防止空指针解引用
|
|
|
+ if (NULL == thread) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
pthread_mutex_lock(&(thread->mutex));
|
|
|
pthread_cond_wait(&(thread->cond), &(thread->mutex));
|
|
|
pthread_mutex_unlock(&(thread->mutex));
|
|
|
@@ -47,7 +59,11 @@ void platform_thread_stop(platform_thread_t* thread)
|
|
|
|
|
|
void platform_thread_start(platform_thread_t* thread)
|
|
|
{
|
|
|
- pthread_mutex_lock(&(thread->mutex));
|
|
|
+ // 添加 NULL 检查,防止空指针解引用
|
|
|
+ if (NULL == thread) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ pthread_mutex_lock(&(thread->mutex));
|
|
|
pthread_cond_signal(&(thread->cond));
|
|
|
pthread_mutex_unlock(&(thread->mutex));
|
|
|
}
|