diff --git a/main.c b/main.c index 2634f397..42f33092 100644 --- a/main.c +++ b/main.c @@ -29,6 +29,7 @@ int main (int argc, char* argv[]) { logg("FTL hash: %s", GIT_VERSION); logg("FTL date: %s", GIT_DATE); logg("FTL user: %s", username); + init_thread_lock(); // pihole-FTL should really be run as user "pihole" to not mess up with the file permissions // still allow this if "debug" flag is set diff --git a/routines.h b/routines.h index 356359a1..61878d2a 100644 --- a/routines.h +++ b/routines.h @@ -61,6 +61,7 @@ char* find_equals(const char* s); void enable_thread_lock(const char *message); void disable_thread_lock(const char *message); +void init_thread_lock(void); void read_FTLconf(void); diff --git a/threads.c b/threads.c index fd85e1d3..f40d62e8 100644 --- a/threads.c +++ b/threads.c @@ -14,23 +14,36 @@ // Any of the various threads (logparser, GC, client threads) is accessing FTL's data structure. Hence, they should // never run at the same time since the data can change half-way through, leading to unspecified behavior. // threadlock: The threadlock ensures that only one thread can be active at any given time -bool threadlock = false; +pthread_mutex_t threadlock; void enable_thread_lock(const char *message) { - while(threadlock) sleepms(5); + int ret = pthread_mutex_lock(&threadlock); + + if(ret != 0) + logg("Thread lock error: %i",ret); if(debugthreads) - logg("Thread lock enabled: %s", message); - - // Set threadlock - threadlock = true; + logg("Thread locked: %s", message); } void disable_thread_lock(const char *message) { - threadlock = false; + int ret = pthread_mutex_unlock(&threadlock); + + if(ret != 0) + logg("Thread unlock error: %i",ret); if(debugthreads) - logg("Thread lock disabled: %s", message); + logg("Thread unlocked: %s", message); +} + +void init_thread_lock(void) +{ + if (pthread_mutex_init(&threadlock, NULL) != 0) + { + logg("FATAL: Thread mutex init failed\n"); + // Return failure + exit(EXIT_FAILURE); + } }