diff options
author | Thomas Haller <thaller@redhat.com> | 2019-01-15 14:53:46 +0100 |
---|---|---|
committer | Thomas Haller <thaller@redhat.com> | 2019-02-05 08:18:07 +0100 |
commit | 61e76e97dc33bb0c3ef698d3b967723c77656a2a (patch) | |
tree | 092e923f73fecdfbd527d5041361f998015003a6 /shared/nm-utils/nm-shared-utils.c | |
parent | 953dd4ac49f7dac8e369f9037dc86ee90a0573d6 (diff) | |
download | NetworkManager-61e76e97dc33bb0c3ef698d3b967723c77656a2a.tar.gz |
shared: add nm_utils_gettid() and NM_ASSERT_ON_MAIN_THREAD()
Diffstat (limited to 'shared/nm-utils/nm-shared-utils.c')
-rw-r--r-- | shared/nm-utils/nm-shared-utils.c | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/shared/nm-utils/nm-shared-utils.c b/shared/nm-utils/nm-shared-utils.c index c9ef89e96c..23c16b6b44 100644 --- a/shared/nm-utils/nm-shared-utils.c +++ b/shared/nm-utils/nm-shared-utils.c @@ -27,6 +27,7 @@ #include <arpa/inet.h> #include <poll.h> #include <fcntl.h> +#include <sys/syscall.h> /*****************************************************************************/ @@ -38,6 +39,57 @@ const NMIPAddr nm_ip_addr_zero = { 0 }; /*****************************************************************************/ +pid_t +nm_utils_gettid (void) +{ + return (pid_t) syscall (SYS_gettid); +} + +/* Used for asserting that this function is called on the main-thread. + * The main-thread is determined by remembering the thread-id + * of when the function was called the first time. + * + * When forking, the thread-id is again reset upon first call. */ +gboolean +_nm_assert_on_main_thread (void) +{ + G_LOCK_DEFINE_STATIC (lock); + static pid_t seen_tid; + static pid_t seen_pid; + pid_t tid; + pid_t pid; + gboolean success = FALSE; + + tid = nm_utils_gettid (); + nm_assert (tid != 0); + + G_LOCK (lock); + + if (G_LIKELY (tid == seen_tid)) { + /* we don't care about false positives (when the process forked, and the thread-id + * is accidentally re-used) . It's for assertions only. */ + success = TRUE; + } else { + pid = getpid (); + nm_assert (pid != 0); + + if ( seen_tid == 0 + || seen_pid != pid) { + /* either this is the first time we call the function, or the process + * forked. In both cases, remember the thread-id. */ + seen_tid = tid; + seen_pid = pid; + success = TRUE; + } + } + + G_UNLOCK (lock); + + return success; +} + +/*****************************************************************************/ + void nm_utils_strbuf_append_c (char **buf, gsize *len, char c) { |