Show human-readable thread ID in log messages.

This helps debug some multithreading issues.
This commit is contained in:
Jordan Bancino 2023-05-27 17:10:07 +00:00
parent 5694a609eb
commit c5cfdb9894
4 changed files with 46 additions and 3 deletions

View file

@ -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)

View file

@ -24,6 +24,7 @@
#include <Log.h>
#include <Memory.h>
#include <Util.h>
#include <string.h>
#include <time.h>
@ -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:

View file

@ -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;
}

View file

@ -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 */