Skip to content

Commit

Permalink
lock: support naming threads
Browse files Browse the repository at this point in the history
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á <[email protected]>
  • Loading branch information
nunojsa committed Jan 31, 2025
1 parent d2786f4 commit ea3eb7b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
25 changes: 24 additions & 1 deletion lock.c
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -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);
}
Expand All @@ -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);
Expand All @@ -134,7 +157,7 @@ struct iio_thrd * iio_thrd_create(int (*thrd)(void *),
return iio_ptr(ret);
}

/* TODO: Set name */


return iio_thrd;
}
Expand Down

0 comments on commit ea3eb7b

Please sign in to comment.