From ea3eb7b2bf285bd79918677ad29c43e3e17fe484 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Nuno=20S=C3=A1?= Date: Fri, 31 Jan 2025 14:50:17 +0000 Subject: [PATCH] lock: support naming threads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add support for naming threads under Unix. It's done with pthread_setname_np(3) so we need to make sure it's available. On top of that, on linux, we also need to compile lock.c with _GNU_SOURCE. Signed-off-by: Nuno Sá --- CMakeLists.txt | 7 +++++++ lock.c | 25 ++++++++++++++++++++++++- 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 5eee82f7f..f355d368d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -596,6 +596,13 @@ else () endif() target_link_libraries(iio PRIVATE ${PTHREAD_LIBRARIES}) + + include(cmake/Utilities.cmake) + + CHECK_PTHREAD_SET_NAME(HAS_PTHREAD_SETNAME_NP) + if (HAS_PTHREAD_SETNAME_NP AND ${CMAKE_SYSTEM_NAME} MATCHES "Linux") + set_source_files_properties(lock.c PROPERTIES COMPILE_FLAGS -D_GNU_SOURCE) + endif() endif() target_sources(iio PRIVATE lock.c) diff --git a/lock.c b/lock.c index 87e29cb35..71389bf25 100644 --- a/lock.c +++ b/lock.c @@ -27,9 +27,24 @@ struct iio_cond { struct iio_thrd { pthread_t thid; void *d; + /* + * pthread_setname_np(3) does not allow names bigger than 16 + * (at least on linux). + */ + char name[16]; int (*func)(void *); }; +#if defined(HAS_PTHREAD_SETNAME_NP) +#if defined(__APPLE__) +#define iio_thrd_create_set_name(thid, name) pthread_setname_np(name) +#else +#define iio_thrd_create_set_name(thid, name) pthread_setname_np(thid, name) +#endif +#else +#define iio_thrd_create_set_name(thid, name) 0 +#endif + struct iio_mutex * iio_mutex_create(void) { struct iio_mutex *lock = malloc(sizeof(*lock)); @@ -107,6 +122,12 @@ void iio_cond_signal(struct iio_cond *cond) static void * iio_thrd_wrapper(void *d) { struct iio_thrd *thrd = d; + /* + * For Mac, it seems we need to name the thread from the thread + * itself. + */ + if (thrd->name[0] != '\0') + iio_thrd_create_set_name(thrd->thid, thrd->name); return (void *)(intptr_t) thrd->func(thrd->d); } @@ -126,6 +147,8 @@ struct iio_thrd * iio_thrd_create(int (*thrd)(void *), iio_thrd->d = d; iio_thrd->func = thrd; + if (name) + iio_strlcpy(iio_thrd->name, name, sizeof(iio_thrd->name)); ret = pthread_create(&iio_thrd->thid, NULL, iio_thrd_wrapper, iio_thrd); @@ -134,7 +157,7 @@ struct iio_thrd * iio_thrd_create(int (*thrd)(void *), return iio_ptr(ret); } - /* TODO: Set name */ + return iio_thrd; }