From fea25ce5e0dbf44ff2e46a3aa2c60faa39deeb94 Mon Sep 17 00:00:00 2001 From: Dirk Engling Date: Tue, 27 Oct 2026 21:33:04 +0100 Subject: Make global torrent counter atomic and fix the setter and getter --- ot_mutex.c | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/ot_mutex.c b/ot_mutex.c index c44efed..5392264 100644 --- a/ot_mutex.c +++ b/ot_mutex.c @@ -26,7 +26,9 @@ /* Our global all torrents list */ static ot_vector all_torrents[OT_BUCKET_COUNT]; static pthread_mutex_t bucket_mutex[OT_BUCKET_COUNT]; -static size_t g_torrent_count; +/* Every bucket's unlock adjusts this, and a bucket lock only keeps other + threads out of that one bucket, so the counter needs its own protection */ +static _Atomic size_t g_torrent_count; /* Self pipe from opentracker.c */ extern int g_self_pipe[2]; @@ -48,14 +50,15 @@ ot_vector *mutex_bucket_lock_by_hash(ot_hash const hash) { return mutex_bucket_l void mutex_bucket_unlock(int bucket, int delta_torrentcount) { pthread_mutex_unlock(bucket_mutex + bucket); - g_torrent_count += delta_torrentcount; + if (delta_torrentcount) + atomic_fetch_add_explicit(&g_torrent_count, (size_t)delta_torrentcount, memory_order_relaxed); } void mutex_bucket_unlock_by_hash(ot_hash const hash, int delta_torrentcount) { mutex_bucket_unlock(bucket_from_hash(hash), delta_torrentcount); } -size_t mutex_get_torrent_count(void) { return g_torrent_count; } +size_t mutex_get_torrent_count(void) { return atomic_load_explicit(&g_torrent_count, memory_order_relaxed); } /* TaskQueue Magic */ -- cgit v1.3