fix random crashes on pthread_detach() (#16137)
Costa Tsaousis committed
Oct 6, 2023 at 10:12 UTC
3581d73519782b0800f994547e2cdb57c19c74be
1 file changed
+8
-3
libnetdata/threads/threads.c
+8
-3
@@ -9,8 +9,8 @@ static pthread_attr_t *netdata_threads_attr = NULL;
9
10
typedef struct {
11
void *arg;
12
- pthread_t *thread;
12
char tag[NETDATA_THREAD_NAME_MAX + 1];
13
+ SPINLOCK detach_lock;
14
void *(*start_routine) (void *);
15
NETDATA_THREAD_OPTIONS options;
16
} NETDATA_THREAD;
@@ -185,6 +185,7 @@ static void thread_cleanup(void *ptr) {
185
NETDATA_THREAD *info = (NETDATA_THREAD *)ptr;
186
netdata_log_error("THREADS: internal error - thread local variable does not match the one passed to this function. Expected thread '%s', passed thread '%s'", netdata_thread->tag, info->tag);
187
}
188
+ spinlock_lock(&netdata_thread->detach_lock);
189
190
if(!(netdata_thread->options & NETDATA_THREAD_OPTION_DONT_LOG_CLEANUP))
191
netdata_log_info("thread with task id %d finished", gettid());
@@ -199,6 +200,7 @@ static void thread_cleanup(void *ptr) {
200
201
netdata_thread->tag[0] = '\0';
202
203
+ spinlock_unlock(&netdata_thread->detach_lock);
204
freez(netdata_thread);
205
netdata_thread = NULL;
206
}
@@ -281,13 +283,15 @@ static void *netdata_thread_init(void *ptr) {
283
}
284
285
int netdata_thread_create(netdata_thread_t *thread, const char *tag, NETDATA_THREAD_OPTIONS options, void *(*start_routine) (void *), void *arg) {
284
- NETDATA_THREAD *info = mallocz(sizeof(NETDATA_THREAD));
286
+ NETDATA_THREAD *info = callocz(1, sizeof(NETDATA_THREAD));
287
info->arg = arg;
286
- info->thread = thread;
288
info->start_routine = start_routine;
289
info->options = options;
290
strncpyz(info->tag, tag, NETDATA_THREAD_NAME_MAX);
291
292
+ spinlock_init(&info->detach_lock);
293
+ spinlock_lock(&info->detach_lock);
294
+
295
int ret = pthread_create(thread, netdata_threads_attr, netdata_thread_init, info);
296
if(ret != 0)
297
netdata_log_error("failed to create new thread for %s. pthread_create() failed with code %d", tag, ret);
@@ -300,6 +304,7 @@ int netdata_thread_create(netdata_thread_t *thread, const char *tag, NETDATA_THR
304
}
305
}
306
307
+ spinlock_unlock(&info->detach_lock);
308
return ret;
309
}
310