5c6 Subj : Re: Can C++ local static objects be made thread safe? To : comp.programming.threads From : Alexander Terekhov Date : Sat Jan 22 2005 01:43 pm Gianni Mariani wrote: [...] > Is this below going to perform as advertised ? Yeah. As long as it's advertised as totally busted. > ThreadLocal, MemoryBarrierSyncReads and MemoryBarrierSyncWrites > are mythical things at this time. DCSI-TLS doesn't need extra barriers. Here's an illustration using Java's "ThreadLocal": class Foo { private static Foo theInstance; private static final ThreadLocal tlsInstance = new ThreadLocal() { protected synchronized Object initialValue() { if (theInstance == null) theInstance = new Foo(); return theInstance; } }; public static Foo getInstance() { return (Foo)tlsInstance.get(); } } In C++ (and dynamic scope), class stuff : private lazy_mutex { // "create/open named mutex" // trick on windows foo * m_ptr; thread_specific_ptr m_tsp; public: /* ... */ const foo & foo_instance() { foo * ptr; if (!(ptr = m_tsp.get())) { lazy_mutex::guard guard(this); if (!m_ptr) m_ptr = new foo(); m_tsp.set(ptr = m_ptr); } return *ptr; } regards, alexander. . 0