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 authored and dNechita committed Feb 24, 2025
1 parent 0a0c48e commit 2c5c1f8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
7 changes: 7 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,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
24 changes: 23 additions & 1 deletion lock.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@
#include <stdlib.h>
#include <time.h>

#if defined(HAS_PTHREAD_SETNAME_NP)
#ifndef PTHREAD_MAX_NAMELEN_NP
#define PTHREAD_MAX_NAMELEN_NP 16
#endif
#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 {
pthread_mutex_t lock;
};
Expand All @@ -27,6 +40,7 @@ struct iio_cond {
struct iio_thrd {
pthread_t thid;
void *d;
char name[PTHREAD_MAX_NAMELEN_NP];
int (*func)(void *);
};

Expand Down Expand Up @@ -107,6 +121,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 +146,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 +156,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 2c5c1f8

Please sign in to comment.