Re: atomically thread-safe Meyers singleton impl (fixed)...
"Dmitriy V'jukov" <dvyukov@gmail.com> wrote in message
news:c7877461-e97b-40cf-93ff-0523f290fe22@u12g2000prd.googlegroups.com...
On Jul 30, 8:44 am, "Chris Thomasson" <x...@xxx.xxx> wrote:
template<typename T>
struct singleton {
static T* instance() {
static T* volatile this_ptr = NULL;
I think here is a little problem. this_ptr is initialized dynamically,
and this initialization is not thread-safe. So some thread can
overwrite pointer in this_ptr with NULL.
You have to made this_ptr global, not function local, so it will be
initialized with NULL statically before any user code is executed.
Okay. However, by that logic and POSIX compiler magic aside for a moment,
the following is not "technically" thread-safe:
void foo() {
static pthread_mutex_t this_mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&this_mtx);
[...];
pthread_mutex_unlock(&this_mtx);
}
unless the `pthread_mutex_lock()' and `pthread_mutex_unlock()' function
calls explicitly handle the condition you describe; where am I going wrong?
or even:
void foo() {
static atomic_word volatile this_mtx = 0;
while (ATOMIC_SWAP(&this_mtx, 1)) {
sched_yield();
}
[...];
ATOMIC_SWAP(&this_mtx, 0);
}
Could the above deadlock? Or encounter multiple threads within the
critical-section?