2009 Jul 29 - Wed
A Singleton Per Thread
A while ago, I had written about
singletons, and how there isn't something straight-forward in Boost. Recently,
I've seen references to a couple of interesting messages regarding not only singletons, but how to get a singleton per thread.
One starts by considering
Boost Thread Local Storage and how to use it.
Then one can consider the concept of a
thread-safe lazy singleton template class from the Boost Cookbook, which
a singleton implementation not referenced in my other article.
Rutger ter Borg suggested the following untested possible code snippet:
template< typename Singleton >
Singleton& get_singleton() {
static boost::thread_specific_ptr< Singleton > m_singleton;
if ( !m_singleton.get() ) {
m_singleton.reset( new Singleton() );
}
return *m_singleton;
}
|