From b3efd67e4bdcfc3664429b71d050abf7ffa5728c Mon Sep 17 00:00:00 2001 From: Donald Buczek Date: Sun, 8 Oct 2017 16:47:44 +0200 Subject: [PATCH] main:cpp: Fix thread race There is some a global variable read_time which is updated by all threads without proper synchronization. WARNING: ThreadSanitizer: data race (pid=15896) Read of size 4 at 0x00000066d53c by thread T7: #0 t_PairAlign(void*) /scratch/cluster/buczek/bsmap/bsmap.git/main.cpp:118 (bsmap+0x00000042c4f2) Previous write of size 4 at 0x00000066d53c by thread T6: [failed to restore the stack] Location is global 'read_time' of size 4 at 0x00000066d53c (bsmap+0x00000066d53c) Thread T7 (tid=15960, running) created by main thread at: #0 pthread_create /scratch/local/bee-root/gcc/gcc-5.3.0-0/source/libsanitizer/tsan/tsan_interceptors.cc:895 (libtsan.so.0+0x000000026c44) #1 Do_PairAlign() /scratch/cluster/buczek/bsmap/bsmap.git/main.cpp:128 (bsmap+0x00000042c613) #2 RunProcess() /scratch/cluster/buczek/bsmap/bsmap.git/main.cpp:499 (bsmap+0x0000004306b0) #3 main /scratch/cluster/buczek/bsmap/bsmap.git/main.cpp:611 (bsmap+0x0000004320ae) Thread T6 (tid=15959, finished) created by main thread at: #0 pthread_create /scratch/local/bee-root/gcc/gcc-5.3.0-0/source/libsanitizer/tsan/tsan_interceptors.cc:895 (libtsan.so.0+0x000000026c44) #1 Do_PairAlign() /scratch/cluster/buczek/bsmap/bsmap.git/main.cpp:128 (bsmap+0x00000042c613) #2 RunProcess() /scratch/cluster/buczek/bsmap/bsmap.git/main.cpp:499 (bsmap+0x0000004306b0) #3 main /scratch/cluster/buczek/bsmap/bsmap.git/main.cpp:611 (bsmap+0x0000004320ae) SUMMARY: ThreadSanitizer: data race /scratch/cluster/buczek/bsmap/bsmap.git/main.cpp:118 t_PairAlign(void*) ================== This is not a real issue, because the value is not currently used. But because we are holding the mutex_fout mutex at this point in code anyway, swap the order and work in the global first, then release the mutex. This puts read_time under the protection of mutex_fout. --- main.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/main.cpp b/main.cpp index aeba443..1c19b66 100644 --- a/main.cpp +++ b/main.cpp @@ -77,8 +77,8 @@ void *t_SingleAlign(void *tid) { } pthread_mutex_lock(&mutex_fout); n_aligned+=a.n_aligned; n_unique+=a.n_unique; n_multiple+=a.n_multiple; - pthread_mutex_unlock(&mutex_fout); read_time+=Cal_AllTime()-ref_time; + pthread_mutex_unlock(&mutex_fout); return NULL; }; @@ -115,8 +115,8 @@ void *t_PairAlign(void *tid) { n_aligned_pairs+=a.n_aligned_pairs; n_unique_pairs+=a.n_unique_pairs; n_multiple_pairs+=a.n_multiple_pairs; n_aligned_a+=a.n_aligned_a; n_unique_a+=a.n_unique_a; n_multiple_a+=a.n_multiple_a; n_aligned_b+=a.n_aligned_b; n_unique_b+=a.n_unique_b; n_multiple_b+=a.n_multiple_b; - pthread_mutex_unlock(&mutex_fout); read_time+=Cal_AllTime()-ref_time; + pthread_mutex_unlock(&mutex_fout); return NULL; };