Re: N2444/Boost: fast_pthread_once and atomicity w/ regard to threads
[added comp.programming.threads; is that okay?]
{ The clc++m moderator is seeing only clc++m. -mod }
<bachlipp@gmail.com> wrote in message
news:b9a4b2f7-95f8-4a51-a459-84ffd9576842@f36g2000hsa.googlegroups.com...
Dear C++ memory model experts,
yesterday I skimmed through the sources of the latest Boost.Thread
library, especially the POSIX Threads implementation of
boost::call_once(). It fundamentally changed in the past. The current
implementation quotes the ISO/IEC JTC1 SC22 WG21 N2444 document
(<http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2444.html>)
and uses an algorithm by Mike Burrow published there.
[...]
AFAICT, this is not "100%" POSIX compliant. There is a rule... You cannot
read or write a memory location that might be updated by another thread
without a lock; simple. BTW, there are ways to implement a lock without
using a memory barrier:
http://blogs.sun.com/dave/resource/Asymmetric-Dekker-Synchronization.txt
http://groups.google.com/group/comp.programming.threads/browse_frm/thread/22b2736484af3ca6
You use an asymmetric model, and elect a "dominate" thread. Also, I am not
sure if this is anything all that new:
http://groups.google.com/group/comp.programming.threads/browse_frm/thread/98815a326299c723
Basically, you can do it like:
<crude code-sketch>
________________________________________________________________
template<typename T>
static T* once() {
static T* g_object = NULL;
static __thread bool g_flag = false;
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
if (! g_flag) {
pthread_mutex_lock(&g_lock);
if (! g_object) {
T* l_object;
try {
l_object = new T;
} catch(...) {
pthread_mutex_unlock(&g_lock);
throw;
}
g_object = l_object;
}
pthread_mutex_unlock(&g_lock);
g_flag = true;
}
return g_object;
}
________________________________________________________________
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]