Re: Will Modern C++ Design ever get fixed? Organization: unknown
"Miles Bader" <miles@gnu.org> wrote in message news:87iq0opl43.fsf@catnip.gol.com...
Andy Venikov <swojchelowek@gmail.com> writes:
I'm sorry, but your code snipped does not represent Doubly-Checked
Locking Pattern. The whole idea of DCLP is to forgo the locking in
case when "shared_field" has been initialized. Your code will take
the lock in any event.
You misunderstand: I was giving only the part of the code that gets
executed in the "slow" case, when shared_field == NULL. I did note
this in my previous message, though perhaps I didn't emphasize it
enough.
I.e., the real code looks like:
[...]
Here is a simple sketch of DCL:
<pseudo-code>
__________________________________________________________________
template<typename T>
static T& once()
{
static atomic<T*> g_global(NULL);
// data-dependant load acquire barrier to sync with release...
T* local = g_global.load(memory_order_consume);
if (! local)
{
static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&g_mutex);
if (! (local = g_global.load(memory_order_relaxed)))
{
try
{
local = new T();
}
catch
{
pthread_mutex_unlock(&g_mutex);
throw;
}
// store release barrier to sync with dependant acquire...
g_global.store(local, memory_order_release);
}
pthread_mutex_unlock(&g_mutex);
}
return *local;
}
__________________________________________________________________
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]