|
From: Schmidt, A. <adr...@si...> - 2016-11-28 14:42:43
|
Dear all,
The program below uses thread-safe static initialization to implement a singleton.
When analyzing this with Helgrind, a data race is reported between the initialization of "val" in the constructor (executed by thread 1) and the increment operation (executed by thread 2). This is expected, as Helgrind does not "understand" the synchronization generated by the compiler.
I'm looking for a way to get rid of the false positives in such cases, and experimented with annotations. I found that placing
ANNOTATE_HAPPENS_AFTER(&inst);
ANNOTATE_HAPPENS_BEFORE(&inst);
inside the getInstance() method (either in this order or reversed) makes the Helgrind warnings disappear.
Is this a valid approach? Are there possible side-effects? Could this "break" the analysis and lead to other data races going undetected?
Thanks,
Adriaan
#include <unistd.h>
#include <pthread.h>
class MySingleton {
public:
MySingleton(int x) : val(x) {
pthread_mutex_init(&lock, NULL);
}
static MySingleton *getInstance() {
static MySingleton inst(0);
//ANNOTATE_HAPPENS_AFTER(&inst);
//ANNOTATE_HAPPENS_BEFORE(&inst);
return &inst;
}
void increment() {
pthread_mutex_lock(&lock);
val++;
pthread_mutex_unlock(&lock);
};
private:
pthread_mutex_t lock;
int val;
};
void *thread_start(void *arg) {
sleep(1);
MySingleton::getInstance()->increment();
}
int main() {
pthread_t a;
pthread_create(&a, NULL, thread_start, NULL);
MySingleton::getInstance();
pthread_join(a, NULL);
}
|
|
From: Norbert R. <Nor...@gm...> - 2022-02-22 16:28:45
|
Dear all, I am analyzing a program with Helgrind for possible data races. Thread-safe static initialization is used to implement singletons inside the code. As expected several false/positves are reported. gcc version: 10.2.1 compile options: -std=c++17 -O3 -m64 -g ... Valgrind version: 3.16.1. So I was searching the mailing list for a possible work around to reduce the number of false/positives reported and found a mail (with identical subject) from Adriaan Schmidt dated 2016-11-28 14:42:43. He used helgrind annotations ANNOTATE_HAPPENS_AFTER and ANNOTATE_HAPPENS_BEFORE to make Helgrind warnings disappear for singletons using thread-safe static initialization. I haven't found any reply to his final question if the solution found could brake the analysis. If I missed the reply please let me know. Thank you in advance. |
|
From: Floyd, P. <pj...@wa...> - 2022-03-01 09:58:28
|
On 2022-02-22 17:28, Norbert Reher wrote: > > So I was searching the mailing list for a possible work around to reduce > the number of false/positives reported and found a mail (with identical > subject) from Adriaan Schmidt dated 2016-11-28 14:42:43. > Not an answer, but just for reference the thread in question can be found here https://sourceforge.net/p/valgrind/mailman/valgrind-users/thread/1C789EC78A01A643ACB88798B277DCED0523382A%40DENBGAT9EL4MSX.ww902.siemens.net/#msg35518667 A+ Paul |