From 5df684b60993f769db94fb12a6ff9e98d22d10a8 Mon Sep 17 00:00:00 2001 From: Jordan Bancino Date: Sat, 27 May 2023 17:10:07 +0000 Subject: [PATCH] Show human-readable thread ID in log messages. This helps debug some multithreading issues. --- Cytoplasm/src/HttpServer.c | 3 --- Cytoplasm/src/Log.c | 3 +++ Cytoplasm/src/Util.c | 32 ++++++++++++++++++++++++++++++++ Cytoplasm/src/include/Util.h | 11 +++++++++++ 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/Cytoplasm/src/HttpServer.c b/Cytoplasm/src/HttpServer.c index e620983..78009f7 100644 --- a/Cytoplasm/src/HttpServer.c +++ b/Cytoplasm/src/HttpServer.c @@ -79,7 +79,6 @@ struct HttpServerContext typedef struct HttpServerWorkerThreadArgs { HttpServer *server; - int id; pthread_t thread; } HttpServerWorkerThreadArgs; @@ -625,7 +624,6 @@ HttpServerEventThread(void *args) } workerThread->server = server; - workerThread->id = i; if (pthread_create(&workerThread->thread, NULL, HttpServerWorkerThread, workerThread) != 0) { @@ -644,7 +642,6 @@ HttpServerEventThread(void *args) int connFd; int pollResult; - pollResult = poll(pollFds, 1, 500); if (pollResult < 0) diff --git a/Cytoplasm/src/Log.c b/Cytoplasm/src/Log.c index 6a441e0..d5a5799 100644 --- a/Cytoplasm/src/Log.c +++ b/Cytoplasm/src/Log.c @@ -24,6 +24,7 @@ #include #include +#include #include #include @@ -316,6 +317,8 @@ Logv(LogConfig * config, int level, const char *msg, va_list argp) } } + StreamPrintf(config->out, "(%lu) ", UtilThreadNo()); + switch (level) { case LOG_EMERG: diff --git a/Cytoplasm/src/Util.c b/Cytoplasm/src/Util.c index 8a1b62d..78c220a 100644 --- a/Cytoplasm/src/Util.c +++ b/Cytoplasm/src/Util.c @@ -244,3 +244,35 @@ UtilGetLine(char **linePtr, size_t * n, Stream * stream) { return UtilGetDelim(linePtr, n, '\n', stream); } + +static void +ThreadNoDestructor(void *p) +{ + Free(p); +} + +unsigned long +UtilThreadNo(void) +{ + static pthread_key_t key; + static int createdKey = 0; + static unsigned long count = 0; + + unsigned long *no; + + if (!createdKey) + { + pthread_key_create(&key, ThreadNoDestructor); + createdKey = 1; + } + + no = pthread_getspecific(key); + if (!no) + { + no = Malloc(sizeof(unsigned long)); + *no = count++; + pthread_setspecific(key, no); + } + + return *no; +} diff --git a/Cytoplasm/src/include/Util.h b/Cytoplasm/src/include/Util.h index 0a3e02d..55c34a9 100644 --- a/Cytoplasm/src/include/Util.h +++ b/Cytoplasm/src/include/Util.h @@ -102,4 +102,15 @@ extern ssize_t UtilGetDelim(char **, size_t *, int, Stream *); */ extern ssize_t UtilGetLine(char **, size_t *, Stream *); +/** + * Get a unique number associated with the current thread. + * Numbers are assigned in the order that threads call this + * function, but are guaranteed to be unique in identifying + * the thread in a more human-readable way than just casting + * the return value of + * .Fn pthread_self + * to a number. + */ +extern unsigned long UtilThreadNo(void); + #endif /* CYTOPLASM_UTIL_H */