
Having considered [ http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt] I propose singleton implementation. I had attached "singleton.hpp" to this letter. Below is the test program: #include <stdio.h> #include <singleton.hpp> class A : public boost::Singleton<A> { // // Only Singleton class can create and delete us! // SINGLETON_IS_MY_FRIEND; public: void foo(){ printf("foo!\n"); } A(){ printf("A()\n"); } ~A(){ printf("~A()\n"); } }; void main() { // It is not compiled: //A a = A::Instance(); // That is exactly as it should be used: A::Instance().foo(); } Test program outputs: A() foo! ~A() I suggest include "singleton.hpp" into "utility.hpp" header that it can be used along with: boost::noncopyable, etc.

On Mon, Jan 25, 2010 at 09:25:51PM +0300, Andrew Chinkoff wrote:
Singleton.hpp have just corrected.
There have been many suggestions in the past of singleton implementations to this list, all flawed in subtle and not so subtle ways. I strongly recommend finding those and the feedback on them and understand them. Your code suffers from among other things. * You do not follow the boost naming_convention. * You use reserved identifiers in several places - __SINGLETON_HPP__, - ___DOOMED_SINGLETON_MUST_NOT_BE_ARRAY___). * Your SINGLETON_IS_MY_FRIEND macro lacks the BOOST_ prefix and could likely be worded better. * Your implementation is rigid and does not have any policies to * indicate whether thread-safety is required, etc. * I'm sure that your CTAssert concept can be replaced by the proper existing Boost implementation of such a compile-time assertion. * Your implementation is limited to types with nullary constructors. Again, I recommend researching why the previous ambitious attempts have not been universally accepted. -- Lars Viklund | zao@acc.umu.se | 070-310 47 07

There have been many suggestions in the past of singleton implementations to this list, all flawed in subtle and not so subtle ways. I strongly recommend finding those and the feedback on them and understand them.
I am newcomer to old.nabble forum. Where can I found these singleton implementation suggestions? -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27320026.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Andrew Chinkoff wrote:
Where can I found these singleton implementation suggestions?
At least one of these suggestions got a formal review: http://lists.boost.org/boost-announce/2008/01/0165.php http://lists.boost.org/boost-announce/2008/01/0171.php But this is just the announce mailing list. You better search for singleton on the developer list for January 2008: http://lists.boost.org/Archives/boost/2008/01/index.php Regards, Thomas

Thank you. I found these suggestions. As often happens, write again - it is easier than learning the old suggestions. I glanced at the debate [http://lists.boost.org/Archives/boost/2008/01/index.php]. And I decided to use self singleton implementation because of: 1) it has already written and usual for me (despite the fact that it is rigid and does not have any policies); 2) at the moment I do not have sufficient time for feedback and understanding the [http://lists.boost.org/Archives/boost/2008/01/index.php] debate (but this is certainly an interesting practice). So, I am to reject my ambitious boost::Singleton request. It remains for my personal use only. P.S.: could anybody tell your experience of Loki::Singleton? -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27321187.html Sent from the Boost - Dev mailing list archive at Nabble.com.

There have been many suggestions in the past of singleton implementations to this list, all flawed in subtle and not so subtle ways. I strongly recommend finding those and the feedback on them and understand them.
I found these suggestions. As often happens, write again - it is easier than learning the old suggestions. I glanced at the debate [http://lists.boost.org/Archives/boost/2008/01/index.php]. And I decided to use self singleton implementation because of: 1) it has already written and usual for me (despite the fact that it is rigid and does not have any policies); 2) at the moment I do not have sufficient time for feedback and understanding the [http://lists.boost.org/Archives/boost/2008/01/index.php] debate (but this is certainly an interesting practice).
Again, I recommend researching why the previous ambitious attempts have not been universally accepted.
So, I am to reject my ambitious boost::Singleton request. It remains for my personal use only. P.S.: could anybody tell your experience of Loki::Singleton? -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27321121.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Personally, I don't feel Boost needs a singleton utility. Singletons themselves aren't *really* ever required. (When have you *actually* required you *cannot* make more than one?) If you don't need more than one, don't make more than one. A singleton takes this idea and forces you to mutilate your class to fulfill some silly requirement. Perhaps some boost::global<T> utility would be better, but a singleton itself is bad practice, in my opinion. boost::global<T> would merely create a global access point to T: typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int It could have policies, to get the advantages of a singleton without the unnecessarily intrusive nature of a singleton. Lazy initialization, thread-safety, etc. On Mon, Jan 25, 2010 at 10:25 AM, Andrew Chinkoff <achinkoff@gmail.com>wrote:
Singleton.hpp have just corrected.
_______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
-- GMan, Nick Gorski

Perhaps some boost::global<T> utility would be better, but a singleton itself is bad practice, in my opinion. boost::global<T> would merely create a global access point to T:
typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int
Perhaps you're right. It is a matter of taste. But I like to write "Object::Instance().get()" rather than "global_object.get()". -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27320129.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Andrew Chinkoff wrote:
Perhaps some boost::global<T> utility would be better, but a singleton itself is bad practice, in my opinion. boost::global<T> would merely create a global access point to T:
typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int
Perhaps you're right. It is a matter of taste. But I like to write "Object::Instance().get()" rather than "global_object.get()".
I've always been mystified as to why a singleton instance is accessed via pointer rather than by reference. Singleton models a one-and-only-one relationship a pointer models a zero-or-one relationship. That said, in my experience singletons are generally used as a crutch to access global state. Jeff

Jeff Flinn wrote:
I've always been mystified as to why a singleton instance is accessed via pointer rather than by reference. Singleton models a one-and-only-one relationship a pointer models a zero-or-one relationship.
I've often thought the same. However, I've always thought the better interface was via a smart pointer. Upon construction, the smart pointer would access the Singleton instance and cache it in a data member. Subsequent access via operator ->() or operator *() would use the data member, thus avoiding the overhead of the instance accessor.
That said, in my experience singletons are generally used as a crutch to access global state.
They do access global state, but there often is global state in an application. If Singletons provide the only means to access state, they formalize that access. Singletons can also, using policies, control lifetime, post-destruction behavior, etc. Consequently, Singletons are more than a crutch, though often overused, abused, or misused. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

However, I've always thought the better interface was via a smart pointer. Upon construction, the smart pointer would access the Singleton instance and cache it in a data member. Subsequent access via operator ->() or operator *() would use the data member, thus avoiding the overhead of the instance accessor.
I think this is unnecessary. The very simple and obvious way is access via reference, don't it?
They do access global state, but there often is global state in an application. If Singletons provide the only > means to access state, they formalize that access. Singletons can also, using policies, control lifetime, post-destruction behavior, etc.
It it really true.
Consequently, Singletons are more than a crutch, though often overused, abused, or misused.
I disagree. -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27324463.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Andrew Chinkoff wrote:
However, I've always thought the better interface was via a smart pointer. Upon construction, the smart pointer would access the Singleton instance and cache it in a data member. Subsequent access via operator ->() or operator *() would use the data member, thus avoiding the overhead of the instance accessor.
I think this is unnecessary. The very simple and obvious way is access via reference, don't it?
I think you missed the point. A typical spelling is some_singleton_class::instance(). That member function must determine whether the Singleton has been instantiated and that, often in a thread safe way. Thus, there's a function call and some sort of synchronized access/manipulation of state. That's costly. In my version, that cost is paid once per context by the smart pointer constructor. All accesses via that smart pointer *do not* incur the instance() overhead.
They do access global state, but there often is global state in an application. If Singletons provide the only > means to access state, they formalize that access. Singletons can also, using policies, control lifetime, post-destruction behavior, etc.
It it really true.
Consequently, Singletons are more than a crutch, though often overused, abused, or misused.
I disagree.
Given your agreement with the foregoing, can I assume your disagreement is with the "often overused, abused, or misused" statement? If so, we're at an impasse. My experience has shown that Singletons are often overused, abused, or misused. Please note that I did not write that they are always so treated. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

I think you missed the point. A typical spelling is some_singleton_class::instance(). That member function must determine whether the Singleton has been instantiated and that, often in a thread safe way. Thus, there's a function call and some sort of synchronized access/manipulation of state. That's costly.
In my version, that cost is paid once per context by the smart pointer constructor. All accesses via that smart pointer *do not* incur the instance() overhead.
Below is the typical realization of A::Instance(): static A& Instance() { if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_); // this is the thread safe cost! instance_ = new A(); } return *instance_; } You should note that: 1) Cost for thread safe synchronization is paid only once. After instance had created this cost is no longer paid. 2) Cost for function call (A::Instance()) is replaced with smart_ptr::get() one. Did I miss the point? -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27325361.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Andrew Chinkoff wrote:
Below is the typical realization of A::Instance():
static A& Instance() { if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_); // this is the thread safe cost! instance_ = new A(); } return *instance_; }
You should note that: 1) Cost for thread safe synchronization is paid only once. After instance had created this cost is no longer paid.
That code has a race condition, so it appears more efficient than it should.
2) Cost for function call (A::Instance()) is replaced with smart_ptr::get() one.
Did I miss the point?
Yes. The smart pointer's operators are inlined functions that merely access a pointer data member. Zero overhead. Your function cannot be inlined and, depending upon how you manage the synchronization, it can be fairly costly, but most certainly includes function call overhead. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tuesday 26 January 2010, Andrew Chinkoff wrote:
Below is the typical realization of A::Instance():
static A& Instance() { if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_); // this is the thread safe cost! instance_ = new A(); } return *instance_; }
You should note that: 1) Cost for thread safe synchronization is paid only once. After instance had created this cost is no longer paid. 2) Cost for function call (A::Instance()) is replaced with smart_ptr::get() one.
Did I miss the point?
First, you are using double-checked locking which is unsafe (google it). Second, using boost::mutex will open you up to problems from the static initialization order fiasco (google it too). You should use boost::once to initialize the singleton object. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAktfGNwACgkQ5vihyNWuA4Vn5gCeKxGYmiiIdEAO2EsZFFt2SjHV fGEAoN0qvVFJl3qGtmGBDufYfTWDZrq6 =WKvK -----END PGP SIGNATURE-----

Thread-safe (instance_ == NULL) comparison: static T& Instance() { /** Perform the Double-Check pattern. See http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt. */ if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_instance_); if (instance_ == NULL) { instance_ = new T(); destroyer_.set_doomed(instance_); } } return *instance_; } -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27327148.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Frank Mori Hess wrote:
You should use boost::once to initialize the singleton object.
Does boost::once ensure that called function will be performed atomically? That is what I mean: A* pa = NULL; void foo(){ pa = new A(); } boost::call_once(foo, flag); Question: Is it true that "pa" will be allocated atomically? Best, Andrew. -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27344908.html Sent from the Boost - Dev mailing list archive at Nabble.com.

AMDG Andrew Chinkoff wrote:
Frank Mori Hess wrote:
You should use boost::once to initialize the singleton object.
Does boost::once ensure that called function will be performed atomically?
That is what I mean:
A* pa = NULL; void foo(){ pa = new A(); } boost::call_once(foo, flag);
Question: Is it true that "pa" will be allocated atomically?
When call_once returns it is guaranteed that foo has run to completion exactly once. If two thread run it in parallel one of them will block while the other runs foo. In Christ, Steven Watanabe

When call_once returns it is guaranteed that foo has run to completion exactly once. If two thread run it in parallel one of them will block while the other runs foo.
Ok, I ask again specifically: Does boost::once ensure that called function will be performed "atomically" rather than "mutually excluded"? I mean "atomic" foo performance but not "mutex'ed". Best, Andrew -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27345500.html Sent from the Boost - Dev mailing list archive at Nabble.com.

AMDG Andrew Chinkoff wrote:
When call_once returns it is guaranteed that foo has run to completion exactly once. If two thread run it in parallel one of them will block while the other runs foo.
Ok, I ask again specifically:
Does boost::once ensure that called function will be performed "atomically" rather than "mutually excluded"?
I don't understand what you mean by "atomically."
I mean "atomic" foo performance but not "mutex'ed".
I can't parse this sentence. In Christ, Steven Watanabe

Steven Watanabe wrote:
Andrew Chinkoff wrote:
When call_once returns it is guaranteed that foo has run to completion exactly once. If two thread run it in parallel one of them will block while the other runs foo.
Ok, I ask again specifically:
Does boost::once ensure that called function will be performed "atomically" rather than "mutually excluded"?
I don't understand what you mean by "atomically."
I mean "atomic" foo performance but not "mutex'ed".
I can't parse this sentence.
I think he means to ask whether it uses CAS and the like versus mutexes. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

Rob Stewart wrote:
I think he means to ask whether it uses CAS and the like versus mutexes. Hi, Rob! For that matter, could you explain me what is "CAS"?
-- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27347363.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Andrew Chinkoff wrote:
Rob Stewart wrote:
I think he means to ask whether it uses CAS and the like versus mutexes.
Hi, Rob! For that matter, could you explain me what is "CAS"?
http://en.wikipedia.org/wiki/Compare-and-swap _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

Ok, I see. I would try to explain. Let us look at pseudo code: *** BEGIN PSEUDO CODE *** static int* my_int = 0; static Mutex mutex; void CreateInt() { if(!my_int) { Locker locker(mutex); if(!my_int) my_int = new int(100); } } void thread_func() { boost::call_once(CreateInt, flag); printf("[%d]", *my_int); } void main() { th1 = create_thread(thread_func); th2 = create_thread(thread_func); while(1) { // Prints "[0][100]", or "[100][0]", or "[100][100]" - hm... undefined! } } *** END OF PSEUDO CODE *** Now I would try to explain the mysterious sense of my "I mean 'atomic' foo performance but not 'mutex'ed'" sentence. *** BEGIN EXPLANATION *** Let us imagine that boost::call_once has approximately this implementation (in pseudo code): call_once(function foo) { if(!called) { Locker locker; if(!called) { called = true; foo(); (1) } } } If you insert foo code at line (1), you will see the cascade of nested blocks like this: if(!flag1) { Locker locker; if(!flag2) // "Double Check Locking" { Locker locker; if(!flag3) // "Triple Check Locking" { Locker locker; ... ... ... foo(); ... ... ... } } } They say, that "Double Check Locking" is not thread-safe. They are right! See [http://www.ibm.com/developerworks/java/library/j-dcl.html] to look at "Double Check Locking" fault. So, "Triple Check Locking", "Quadro Check Locking" etc... are not thread-safe. "Atomic code" means the part of code, that is thread-safe. ATOMIC(code) ensures that "code" will be executed consistently with all threads. "Mutex'ed code" is the part of code, that is protected with mutex locker. I assume that boost::call_once does so: if(ATOMIC(!flag1)) // (2) { Locker locker; ... } I would like to ask Boost.Commutiny - is my assumption at line (2) the true? *** END OF EXPLANATION *** P.S. 1: Sorry for verbosity and complexity, if so. Best, Andrew. -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27347375.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Andrew Chinkoff wrote:
Ok, I see. I would try to explain.
[snip lots of code trying to explain "atomic"]
ATOMIC(code) ensures that "code" will be executed consistently with all threads. "Mutex'ed code" is the part of code, that is protected with mutex locker.
I don't understand the difference between what you describe as ATOMIC(code) and putting "code" into a critical section controlled by a mutex.
I assume that boost::call_once does so:
if(ATOMIC(!flag1)) // (2) { Locker locker; ... }
Steven already noted that call_once ensures that one and only one thread runs the supplied functor; any contending threads block until the functor completes. That's pretty clear. If that's still not what you want to know, I'm at a loss to understand even yet. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

Rob, there is a test program I would to be explained to me: *** BEGIN OF TEST PROGRAM *** #include <stdio.h> #include <boost/thread.hpp> #define USE_SPINLOCKS //#define USE_MUTEXES boost::thread th1; boost::thread th2; boost::mutex mutex; int global_int = 0; bool IsNotEven(int code) { boost::mutex::scoped_lock locker(mutex); bool ret = (code & 1); return ret; } void thread_func() { for(int i = 0; i < 1000000; ++i) { #ifdef USE_MUTEXES if(IsNotEven(global_int)) // (1) #elif defined USE_SPINLOCKS if(__sync_and_and_fetch(&global_int, 1)) // (2) #else ERROR__WRONG_COMPILED; #endif global_int+=9; else global_int+=1; } } int main() { th1 = boost::thread(&thread_func); th2 = boost::thread(&thread_func); th1.join(); th2.join(); printf("global_int = %d\n", global_int); return 0; } *** END OF TEST PROGRAM *** Results of test program: 1) Test program compiled with USE_SPINLOCKS. Outputs are always: "global_int = 10" 2) Test program compiled with USE_MUTEXES. Outputs differ from each other: "global_int = 10000008" "global_int = 10000000" "global_int = 9763210" Could you explain me why outputs produced with USE_SPINLOCKS compilation differ from USE_MUTEXES ones? -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27348736.html Sent from the Boost - Dev mailing list archive at Nabble.com.

I made a mistake with __sync_and_and_fetch, but using __sync_fetch_and_and instead of __sync_and_and_fetch not alter program outputs. -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27348883.html Sent from the Boost - Dev mailing list archive at Nabble.com.

AMDG Andrew Chinkoff wrote:
Ok, I see. I would try to explain.
Let us look at pseudo code:
*** BEGIN PSEUDO CODE *** static int* my_int = 0; static Mutex mutex;
void CreateInt() { if(!my_int) { Locker locker(mutex); if(!my_int) my_int = new int(100); } }
void thread_func() { boost::call_once(CreateInt, flag); printf("[%d]", *my_int); }
void main() { th1 = create_thread(thread_func); th2 = create_thread(thread_func); while(1) { // Prints "[0][100]", or "[100][0]", or "[100][100]" - hm... undefined! } } *** END OF PSEUDO CODE ***
There is no race in this code. It will always print [100][100]. In fact, the code would work equally well if you said: void CreateInt() { my_int = new int(100); } In Christ, Steven Watanabe

AMDG Andrew Chinkoff wrote:
*** BEGIN EXPLANATION *** Let us imagine that boost::call_once has approximately this implementation (in pseudo code):
call_once(function foo) { if(!called) { Locker locker; if(!called) { called = true; foo(); (1) } } }
called = true; has to go /after/ the call to foo. Otherwise, this works once you add in the magic needed to prevent the compiler and the hardware from reordering operations. In Christ, Steven Watanabe

----- Original Message ----- From: "Andrew Chinkoff" <achinkoff@gmail.com> To: <boost@lists.boost.org> Sent: Wednesday, January 27, 2010 10:48 PM Subject: Re: [boost] [Boost.utility]
Ok, I see. I would try to explain.
Let us look at pseudo code:
<snip>
*** BEGIN EXPLANATION *** Let us imagine that boost::call_once has approximately this implementation (in pseudo code):
call_once(function foo) { if(!called) { Locker locker; if(!called) { called = true; foo(); (1) } } }
If you insert foo code at line (1), you will see the cascade of nested blocks like this:
if(!flag1) { Locker locker; if(!flag2) // "Double Check Locking" { Locker locker; if(!flag3) // "Triple Check Locking" { Locker locker; ... ... ... foo(); ... ... ... } } }
<snip>
I assume that boost::call_once does so:
if(ATOMIC(!flag1)) // (2) { Locker locker; ... }
I would like to ask Boost.Commutiny - is my assumption at line (2) the true? *** END OF EXPLANATION ***
P.S. 1: Sorry for verbosity and complexity, if so.
Andrew, you don't need to make supossitions on how call_once works. Just see the current implementation for Posix systems (extracted from boost/thread/posinx/once.hpp): template<typename Function> void call_once(once_flag& flag,Function f) { static boost::uintmax_t const uninitialized_flag=BOOST_ONCE_INITIAL_FLAG_VALUE; static boost::uintmax_t const being_initialized=uninitialized_flag+1; boost::uintmax_t const epoch=flag.epoch; boost::uintmax_t& this_thread_epoch=detail::get_once_per_thread_epoch(); if(epoch<this_thread_epoch) { pthread::pthread_mutex_scoped_lock lk(&detail::once_epoch_mutex); while(flag.epoch<=being_initialized) { if(flag.epoch==uninitialized_flag) { flag.epoch=being_initialized; try { pthread::pthread_mutex_scoped_unlock relocker(&detail::once_epoch_mutex); f(); } catch(...) { flag.epoch=uninitialized_flag; BOOST_VERIFY(!pthread_cond_broadcast(&detail::once_epoch_cv)); throw; } flag.epoch=--detail::once_global_epoch; BOOST_VERIFY(!pthread_cond_broadcast(&detail::once_epoch_cv)); } else { while(flag.epoch==being_initialized) { BOOST_VERIFY(!pthread_cond_wait(&detail::once_epoch_cv,&detail::once_epoch_mutex)); } } } this_thread_epoch=detail::once_global_epoch; } } Now you can make a concrete request on a concrete implementation. Best, Vicente

Andrew Chinkoff wrote:
Below is the typical realization of A::Instance():
static A& Instance() { if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_); // this is the thread safe cost! instance_ = new A(); } return *instance_; } [...] Did I miss the point?
I guess the people sent you references with the expectation that you actually read them. The "typical realization of A::Instance()" you presented has two serious race conditions. 1) As implemented above, more than one thread can try to create the instance of A, and the last one trying will be the one that creates the instance that will finally survive. The other instances will live forever, since no reference to them exists any more, and nobody is responsible to delete them. 2) Even worse and much more difficult to fix, you will have a hard time forcing the compiler to not first allocate the space for the instance of A, then set the instance_ pointer to it, and then construct A in the newly allocated space. (And the next thread will see that instance_ is no longer NULL, and use the not yet constructed object.) You would basically need support for atomic operations to force the compiler to do the thing you want it to do. Regards, Thomas

Thread-safe (instance_ == NULL) comparison: static T& Instance() { /** Perform the Double-Check pattern. See http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt. */ if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_instance_); if (instance_ == NULL) { instance_ = new T(); destroyer_.set_doomed(instance_); } } return *instance_; } -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27327109.html Sent from the Boost - Dev mailing list archive at Nabble.com.

----- Original Message ----- From: "Andrew Chinkoff" <achinkoff@gmail.com> To: <boost@lists.boost.org> Sent: Tuesday, January 26, 2010 7:07 PM Subject: Re: [boost] [Boost.utility]
Thread-safe (instance_ == NULL) comparison:
static T& Instance() { /** Perform the Double-Check pattern. See http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt. */ if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_instance_); if (instance_ == NULL) { instance_ = new T(); destroyer_.set_doomed(instance_); } } return *instance_; }
The paper you point (http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt.) presumes at least that: static T& Instance() { /** Perform the Double-Check pattern. See */ if ( ATOMIC(instance_ == NULL)) { boost::mutex::scoped_lock locker(mtx_instance_); if (ATOMIC(instance_ == NULL)) { T* tmp = new T()); (1) ATOMIC(instance_ = tmp); (2) destroyer_.set_doomed(instance_); } } return *instance_; } Where (2) must be executed after (1). It is a known issue that these operations are not always atomic (as they depend on the architecture and even on the optimization options). So to be portable you will need to define instance_ as atomic<T*>. In this case call instance() each time will be more expensive calling it once, store it in a smart pointer and then get this pointer from the stack. the use could be something like class S : singleton<T> {...}; S::smart_ptr ptr; use ptr to access the single instance of S. To get the same performances without the smart pointer you will need the following S* ptr=S::instance(); Best, Vicente

Thanks for the clarification! Best, Andrew. -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27329205.html Sent from the Boost - Dev mailing list archive at Nabble.com.

----- Original Message ----- From: "Andrew Chinkoff" <achinkoff@gmail.com> To: <boost@lists.boost.org> Sent: Tuesday, January 26, 2010 5:22 PM Subject: Re: [boost] [Boost.utility]
I think you missed the point. A typical spelling is some_singleton_class::instance(). That member function must determine whether the Singleton has been instantiated and that, often in a thread safe way. Thus, there's a function call and some sort of synchronized access/manipulation of state. That's costly.
In my version, that cost is paid once per context by the smart pointer constructor. All accesses via that smart pointer *do not* incur the instance() overhead.
Below is the typical realization of A::Instance():
static A& Instance() { if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_); // this is the thread safe cost! instance_ = new A(); } return *instance_; }
You should note that: 1) Cost for thread safe synchronization is paid only once. After instance had created this cost is no longer paid. 2) Cost for function call (A::Instance()) is replaced with smart_ptr::get() one.
Did I miss the point?
Hi, the test (instance_ == NULL) will be thread-safe only if instance comparation and asignement are atomic. So the smart pointer trick will always improve performances as the stored instance is local to the thread as it is stored on the stack. Best, Vicente

Thread-safe (instance_ == NULL) comparison: static T& Instance() { /** Perform the Double-Check pattern. See http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt. */ if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_instance_); if (instance_ == NULL) { instance_ = new T(); destroyer_.set_doomed(instance_); } } return *instance_; } -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27327050.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Andrew Chinkoff wrote:
static T& Instance() { /** Perform the Double-Check pattern. See http://www.research.ibm.com/designpatterns/pubs/ph-jun96.txt. */ if (instance_ == NULL) { boost::mutex::scoped_lock locker(mtx_instance_); if (instance_ == NULL) { instance_ = new T(); destroyer_.set_doomed(instance_); } } return *instance_; }
Please! Go back and read the references you were given before. The double-checked locking pattern *is not safe*. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

Stewart, Robert wrote:
Jeff Flinn wrote:
That said, in my experience singletons are generally used as a crutch to access global state.
They do access global state, but there often is global state in an application. If Singletons provide the only means to access state, they formalize that access. Singletons can also, using policies, control lifetime, post-destruction behavior, etc. Consequently, Singletons are more than a crutch, though often overused, abused, or misused.
Well, I've yet to come across a case where global state couldn't have been avoided by passing the appropriate objects by value or reference along the function call chain. Doing so avoids the mess that ensues when trying to unit test classes and functions that use supposed singletons/global state. Jeff

Jeff Flinn wrote:
Stewart, Robert wrote:
Jeff Flinn wrote:
That said, in my experience singletons are generally used as a crutch to access global state.
They do access global state, but there often is global state in an application. If Singletons provide the only means to access state, they formalize that access. Singletons can also, using policies, control lifetime, post-destruction behavior, etc. Consequently, Singletons are more than a crutch, though often overused, abused, or misused.
Well, I've yet to come across a case where global state couldn't have been avoided by passing the appropriate objects by value or reference along the function call chain.
That is certainly possible. It is also possible to use return codes rather than exceptions for all error reporting, though that's hardly a good idea. Throwing exceptions and catching them in higher level code means the code in the middle is ignorant of the error state. Singletons work similarly. Code buried well down the call stack needs access to some state. Without a Singleton for that state, all functions up the call stack must be changed to pass along that state. Using Singletons eliminates that burden.
Doing so avoids the mess that ensues when trying to unit test classes and functions that use supposed singletons/global state.
I can't argue with that. It is also easier to unit test functions returning error codes, but that shouldn't be the only factor in design. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

Rob Stewart wrote:
Doing so avoids the mess that ensues when trying to unit test classes and functions that use supposed singletons/global state.
I can't argue with that. It is also easier to unit test functions returning error codes, but that shouldn't be the only factor in design.
??? A try/catch block may not be beautiful, but calling it a mess like trying to unit test a side-effect full function doesn't seem appropriate. Regards, Thomas

Thomas Klimpel wrote:
Rob Stewart wrote:
Doing so avoids the mess that ensues when trying to unit test classes and functions that use supposed singletons/global state.
It is also easier to unit test functions returning error codes, but that shouldn't be the only factor in design.
A try/catch block may not be beautiful, but calling it a mess like trying to unit test a side-effect full function doesn't seem appropriate.
The OP didn't mention all he included in "the mess" but just taking exception handling, you need a handler for each potential exception, which leads to duplicate test assertion logic or translating the emission of a particular exception into a numeric/enumerated value that later conditional logic decodes. Either way, that quickly becomes a mess. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

Stewart, Robert wrote:
Jeff Flinn wrote:
Stewart, Robert wrote:
Jeff Flinn wrote:
That said, in my experience singletons are generally used as a crutch to access global state. They do access global state, but there often is global state in an application. If Singletons provide the only means to access state, they formalize that access. Singletons can also, using policies, control lifetime, post-destruction behavior, etc. Consequently, Singletons are more than a crutch, though often overused, abused, or misused. Well, I've yet to come across a case where global state couldn't have been avoided by passing the appropriate objects by value or reference along the function call chain.
That is certainly possible. It is also possible to use return codes rather than exceptions for all error reporting, though that's hardly a good idea. Throwing exceptions and catching them in higher level code means the code in the middle is ignorant of the error state. Singletons work similarly. Code buried well down the call stack needs access to some state. Without a Singleton for that state, all functions up the call stack must be changed to pass along that state. Using Singletons eliminates that burden.
I fail to see the analogy between global-state-coupling and exceptions. In the former, you've got a function with dependency upon global state, and any function that calls that function is now dependent upon global state. The only way I can tell that dependency is I have to hunt that down by looking at the source code, or trying to link and getting an unresolved ref liner error. How are exceptions similar? What use cases do you see where global state access is required?
Doing so avoids the mess that ensues when trying to unit test classes and functions that use supposed singletons/global state.
I can't argue with that. It is also easier to unit test functions returning error codes, but that shouldn't be the only factor in design.
I can just as easily test that a function does or does not throw given a set of arguments as I can test that I get the proper return values. Most unit test libraries specifically provide exception support. Jeff

Jeff Flinn wrote:
I fail to see the analogy between global-state-coupling and exceptions. In the former, you've got a function with dependency upon global state, and any function that calls that function is now dependent upon global state. The only way I can tell that dependency is I have to hunt that down by looking at the source code, or trying to link and getting an unresolved ref liner error. How are exceptions similar?
Let me try another way to explain my point. In the case of return codes, you must litter every function in the call chain with the appropriate return type. Each function in the chain must examine the returned value to determine whether to proceed or return an error. With exceptions, intermediate functions are ignorant of the exceptions thrown or the code that handles them. With Singletons, code that needs access to global state accesses a Singleton. Without that, all intermediate functions must be littered with argument(s) for the state needed by the inner function. If the inner function needs access to global state it didn't need before, or no longer needs access to global state it once did, all functions in the call stack must be changed to pass or not pass along that state. I was never discussing determining whether a function is dependent upon global state.
What use cases do you see where global state access is required?
Consider an environment with a single configuration state object. All code requiring access to that configuration state can either access it as global state, which it is, or that object can be passed to all functions that require it. The latter leads to polluting myriad other functions with arguments they need only to satisfy the functions they call. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

----- Original Message ----- From: "Stewart, Robert" <Robert.Stewart@sig.com> To: <boost@lists.boost.org> Sent: Tuesday, January 26, 2010 5:46 PM Subject: Re: [boost] [Boost.utility]
Jeff Flinn wrote:
I fail to see the analogy between global-state-coupling and exceptions. In the former, you've got a function with dependency upon global state, and any function that calls that function is now dependent upon global state. The only way I can tell that dependency is I have to hunt that down by looking at the source code, or trying to link and getting an unresolved ref liner error. How are exceptions similar?
Let me try another way to explain my point.
In the case of return codes, you must litter every function in the call chain with the appropriate return type. Each function in the chain must examine the returned value to determine whether to proceed or return an error. With exceptions, intermediate functions are ignorant of the exceptions thrown or the code that handles them.
With Singletons, code that needs access to global state accesses a Singleton. Without that, all intermediate functions must be littered with argument(s) for the state needed by the inner function. If the inner function needs access to global state it didn't need before, or no longer needs access to global state it once did, all functions in the call stack must be changed to pass or not pass along that state.
I was never discussing determining whether a function is dependent upon global state.
What use cases do you see where global state access is required?
Consider an environment with a single configuration state object. All code requiring access to that configuration state can either access it as global state, which it is, or that object can be passed to all functions that require it. The latter leads to polluting myriad other functions with arguments they need only to satisfy the functions they call.
What about defining all the functions of the singleton at a namespace level. So rather than doing struct S : singleton<S> { void f1(); int f2(char); }; and use it as S::instance().f1(); doing in this way namespace S { void f1(); int f2(char); }; and use it as S::f1(); Of course, nothing forbids the implementation of the functions at the namespace level to use a singleton, but this is an internal detail, not shown at the user level. What use cases do you see where the class interface is more convenient than the namespace interface? Best, Vicente

vicente.botet wrote:
What about defining all the functions of the singleton at a namespace level. So rather than doing
struct S : singleton<S> { void f1(); int f2(char); };
and use it as
S::instance().f1();
doing in this way
namespace S { void f1(); int f2(char); };
and use it as
S::f1();
Of course, nothing forbids the implementation of the functions at the namespace level to use a singleton, but this is an internal detail, not shown at the user level.
What use cases do you see where the class interface is more convenient than the namespace interface?
What you've shown is simply a variation of Monostate. What's missing is any opportunity to inline functions because the state must be in the implementation file. (The state could be put in an "off limits" nested namespace, but that's easy to violate, so a poor design.) Aside from the possible loss of efficiency, there's no great disadvantage, though some Singleton designs allow for objects that are destroyed by atexit(), that can be resurrected if needed after being destroyed (due to another static scope object outliving the first instance), etc. Most of those things are overly complicated, however. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

Stewart, Robert wrote:
Jeff Flinn wrote:
I fail to see the analogy between global-state-coupling and exceptions. In the former, you've got a function with dependency upon global state, and any function that calls that function is now dependent upon global state. The only way I can tell that dependency is I have to hunt that down by looking at the source code, or trying to link and getting an unresolved ref liner error. How are exceptions similar?
Let me try another way to explain my point.
In the case of return codes, you must litter every function in the call chain with the appropriate return type. Each function in the chain must examine the returned value to determine whether to proceed or return an error. With exceptions, intermediate functions are ignorant of the exceptions thrown or the code that handles them.
I'm aware of the effects of return codes vs exceptions.
With Singletons, code that needs access to global state accesses a Singleton. Without that, all intermediate functions must be littered with argument(s) for the state needed by the inner function. If the inner function needs access to global state it didn't need before, or no longer needs access to global state it once did, all functions in the call stack must be changed to pass or not pass along that state.
Isn't your first sentence exactly defining singleton abuse... using a singleton as glorified global data access? The major tenet that affords functional programming it's power and robustness is that a function depends only upon it's arguments. The Law of Demeter provides the extension for OO that member functions are allowed to depend upon it's object's(this) state and it's arguments. What makes the singleton's functionality so different from any other arguments or object data members that you don't want to make them just as visible? Yes, system's change, that's why there are refactoring tools and IDE's. If you find yourself with such a brittle system, fix the design. If you just want a quick and dirty hack en lieu of proper design, I guess you can use global data access, but don't dress it up as anything but the hack that it is. Open the back door and let chaos to ensue.
I was never discussing determining whether a function is dependent upon global state.
That's how the singleton has been used in this thread AFAICT.
What use cases do you see where global state access is required?
Consider an environment with a single configuration state object. All code requiring access to that configuration state can either access it as global state, which it is, or that object can be passed to all functions that require it. The latter leads to polluting myriad other functions with arguments they need only to satisfy the functions they call.
That's not a very concrete use case. I contend that this "single configuration state object", really isn't an object. It's just an ad hoc collection of data with no encapsulation, no enforceable class invariants, no behavior. The singleton usage pollutes any functions that use it with a myriad of types that aren't relevant to their responsibilities. Are you saying that getting rid of "arguments they need only to satisfy the functions they call" at the expense of increased hidden coupling is a more valid design decision? Jeff

Jeff Flinn wrote:
Stewart, Robert wrote:
Jeff Flinn wrote:
With Singletons, code that needs access to global state accesses a Singleton. Without that, all intermediate functions must be littered with argument(s) for the state needed by the inner function. If the inner function needs access to global state it didn't need before, or no longer needs access to global state it once did, all functions in the call stack must be changed to pass or not pass along that state.
Isn't your first sentence exactly defining singleton abuse... using a singleton as glorified global data access?
What else is the point of Singleton? It is for common access to a single, global object. [snip diatribe insinuating that any use of global state versus FP approach is bad design.]
I was never discussing determining whether a function is dependent upon global state.
That's how the singleton has been used in this thread AFAICT.
That's incorrect. The thread was discussing *using* Singleton to access global state. It wasn't about determining *whether* a function is dependent upon global state.
What use cases do you see where global state access is required?
Consider an environment with a single configuration state object. All code requiring access to that configuration state can either access it as global state, which it is, or that object can be passed to all functions that require it. The latter leads to polluting myriad other functions with arguments they need only to satisfy the functions they call.
That's not a very concrete use case.
It seems quite concrete to me. I'm not sure how I can make it less abstract for you. It is a Singleton instance of a class that manages the application configuration data.
I contend that this "single configuration state object", really isn't an object. It's just an ad hoc collection of data with no encapsulation, no enforceable class invariants, no behavior. The singleton usage pollutes any functions that use it with a myriad of types that aren't relevant to their responsibilities. Are you
The configuration data is managed by a class with accessors of various sorts for the data. Some of the data structures are ad hoc, in that they apply specifically to the hive of data representing the configuration data, but they are not just tossed together in an arbitrary way, just to make things work (which is what most people think "ad hoc" means). The class encapsulates a great deal, enforces many invariants, and has a great deal of behavior. So much for your contention.
saying that getting rid of "arguments they need only to satisfy the functions they call" at the expense of increased hidden coupling is a more valid design decision?
Absolutely yes, when those extra arguments are otherwise a few, well-known Singletons. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

I've always been mystified as to why a singleton instance is accessed via pointer rather than by reference.
I think that reference access is more reliable than pointer one because references are only aliases but pointers are actual 4 (or 8) bytes objects. Aliases can not be copied but pointers do.
Singleton models a one-and-only-one relationship a pointer models a zero-or-one relationship. That said, in my experience singletons are generally used as a crutch to access global state.
I think that the best way to solve the problem - increase the level of indirection, don't I? Explanation for this should be further. "One-and-only-one" instance is incapsulated inside Singleton class. Singleton class controls access to the instance. How this access is controlled - that is a personal matter of programmer and the task been solving. Global objects are naked instances. For me "global" means "dangerous" but "Singleton" means "flexible" and "safe". -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27323937.html Sent from the Boost - Dev mailing list archive at Nabble.com.

I've always been mystified as to why a singleton instance is accessed via pointer rather than by reference. Singleton models a one-and-only-one relationship a pointer models a zero-or-one relationship. That said, in my experience singletons are generally used as a crutch to access global state. I use them in a game to access part of the global state from a different
Jeff Flinn wrote: part. For example, the part that does random numbers keeps state, and for various reasons, given a particular seed must be deterministic, so there can be only one. It's single threaded though. I store an instance as a pointer, but return it from the singlecrutch <grin;> as reference. Patrick

Andrew Chinkoff wrote:
Perhaps some boost::global<T> utility would be better, but a singleton itself is bad practice, in my opinion. boost::global<T> would merely create a global access point to T:
typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int
Perhaps you're right. It is a matter of taste. But I like to write "Object::Instance().get()" rather than "global_object.get()".
One requires creating a new tailored object, the other adapts itself to any object un-intrusively. So it's pretty obvious global<int>.get() is better, and not just a matter of taste.

-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tuesday 26 January 2010, Mathias Gaunard wrote:
Andrew Chinkoff wrote:
Perhaps some boost::global<T> utility would be better, but a singleton itself is bad practice, in my opinion. boost::global<T> would merely create a global access point to T:
typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int
Perhaps you're right. It is a matter of taste. But I like to write "Object::Instance().get()" rather than "global_object.get()".
One requires creating a new tailored object, the other adapts itself to any object un-intrusively.
So it's pretty obvious global<int>.get() is better, and not just a matter of taste.
One of the motivations for the singleton pattern is making it impossible to instantiate more than one instance of the class, which something which is unintrusive cannot accomplish. Maybe I'm missing something however, as I don't see the point of boost::global<T> at all? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAktfBtsACgkQ5vihyNWuA4UYBQCeKxymd1XF8vzv9bANsit8PVzY FfsAoLgya2s7VtUpbSKw+3oT/d5NiNFa =Uv2d -----END PGP SIGNATURE-----

Ok, so what's the point of making it impossible to instantiate more than one class? Yeah, I get it, you don't need more than one global service; so don't make more than one instance. My argument is that you never truly need to *stop* the instantiation of a class. The global wrapper would merely provide every benefit you can think of in a singleton, without the forceful and wasteful intrusion it has. On Tue, Jan 26, 2010 at 7:14 AM, Frank Mori Hess <frank.hess@nist.gov>wrote:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1
On Tuesday 26 January 2010, Mathias Gaunard wrote:
Andrew Chinkoff wrote:
Perhaps some boost::global<T> utility would be better, but a singleton itself is bad practice, in my opinion. boost::global<T> would merely create a global access point to T:
typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int
Perhaps you're right. It is a matter of taste. But I like to write "Object::Instance().get()" rather than "global_object.get()".
One requires creating a new tailored object, the other adapts itself to any object un-intrusively.
So it's pretty obvious global<int>.get() is better, and not just a matter of taste.
One of the motivations for the singleton pattern is making it impossible to instantiate more than one instance of the class, which something which is unintrusive cannot accomplish. Maybe I'm missing something however, as I don't see the point of boost::global<T> at all?
-----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux)
iEYEARECAAYFAktfBtsACgkQ5vihyNWuA4UYBQCeKxymd1XF8vzv9bANsit8PVzY FfsAoLgya2s7VtUpbSKw+3oT/d5NiNFa =Uv2d -----END PGP SIGNATURE----- _______________________________________________ Unsubscribe & other changes: http://lists.boost.org/mailman/listinfo.cgi/boost
-- GMan, Nick Gorski

GMan wrote:
Ok, so what's the point of making it impossible to instantiate more than one class? Yeah, I get it, you don't need more than one global service; so don't make more than one instance. My argument is that you never truly need to *stop* the instantiation of a class.
More than one instance can lead to unwanted contention, failed synchronization, resource overallocation, etc. If one assumes a single instance, those things are easier to manage. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

Stewart, Robert wrote:
More than one instance can lead to unwanted contention, failed synchronization, resource overallocation, etc. If one assumes a single instance, those things are easier to manage.
I still disagree with this. Just, don't type "some_expensive_resource r;". The programmer should be using a global access point. But even if we don't get past that: It doesn't require we have a singleton class. Imagine the global class I proposed existed. Just take your class and intrude it yourself, making it a singleton. Ta-da! Singleton -> Always intrusive Global -> Not always instruive , can be I think it's clear which is generally more useful.

GMan wrote:
Stewart, Robert wrote:
More than one instance can lead to unwanted contention, failed synchronization, resource overallocation, etc. If one assumes a single instance, those things are easier to manage.
I still disagree with this. Just, don't type "some_expensive_resource r;".
That's easier said than done. There are many developers writing code that do whatever works. If the class permits creating multiple instances, they'll do regardless of whether it's good for them. If the class prevents being used in other than the prescribed manner, then they can't do the wrong thing.
The programmer should be using a global access point. But even if we don't get past that:
It doesn't require we have a singleton class. Imagine the global class I proposed existed. Just take your class and intrude it yourself, making it a singleton. Ta-da!
I'm not sure what semantics you're suggesting for your class. If you described them, I missed it. I'll assume, however, that you're suggested that all instances of global<T> refer to the same instance of T.
Singleton -> Always intrusive Global -> Not always instruive , can be
I think it's clear which is generally more useful.
I think it's clear that both have their uses. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

That's easier said than done. There are many developers writing code that do whatever works. If the class permits creating multiple instances,
Stewart, Robert wrote: they'll do regardless of whether it's good for them. If the class prevents being used in other than the prescribed manner, then they can't do the wrong thing. While I don't support such programming habits...fine, I'll take that as a point. The rest of my post was this: Take your best singleton class, but remove the bit where it intrudes and forces only a single instantiation. Call this "global", which provides the same thing as a singleton but allows other instantiations of the class. My argument was that this class is more worth boost's time than the singleton class. The reason being, users of global could always re-introduce the single-instantiation behavior, but don't have to. This provides more flexibility.

GMan wrote:
Take your best singleton class, but remove the bit where it intrudes and forces only a single instantiation. Call this "global", which provides the same thing as a singleton but allows other instantiations of the class.
OK, so it implicitly instantiates the object on first access, but the instance must be visible to any code interested in using it, right?
My argument was that this class is more worth boost's time than the singleton class. The reason being, users of global could always re-introduce the single-instantiation behavior, but don't have to. This provides more flexibility.
Making a Singleton from a "global" implies somehow enforcing a single instance. Without help from the library, mistakes will happen. Indeed, if a UDT can be adorned in such a way as to prevent its use with anything but the Singleton library, user mistakes can be prevented by design. I'd argue that one is a policy away from the other and that both are useful. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Tuesday 26 January 2010, GMan wrote:
Take your best singleton class, but remove the bit where it intrudes and forces only a single instantiation. Call this "global", which provides the same thing as a singleton but allows other instantiations of the class. My argument was that this class is more worth boost's time than the singleton class. The reason being, users of global could always re-introduce the single-instantiation behavior, but don't have to. This provides more flexibility.
If you peel off the singleton aspect of singletons, you're left with global state and lazy initialization. A facility that supports thread-safe lazy initialization might be useful, but why tie it to global state (which is of more dubious value)? -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEYEARECAAYFAktfYkcACgkQ5vihyNWuA4XUeACdHM9zyWX13SGz5ZF1iHLoWXJz C/cAn05tGtPIN6N7YhF4IrDpnsJN4wqd =rfHe -----END PGP SIGNATURE-----

Frank Mori Hess wrote:
If you peel off the singleton aspect of singletons, you're left with global state and lazy initialization. A facility that supports thread-safe lazy initialization might be useful, but why tie it to global state (which is of more dubious value)?
Hm, good point. Perhaps there are three "levels" here: 1) Thread-safe, lazy initialized, general creation methods 2) 1 with global access 3) 2 with guaranteed same-instance access.

GMan wrote:
Frank Mori Hess wrote:
If you peel off the singleton aspect of singletons, you're left with global state and lazy initialization. A facility that supports thread-safe lazy initialization might be useful, but why tie it to global state (which is of more dubious value)?
Hm, good point. Perhaps there are three "levels" here:
1) Thread-safe, lazy initialized, general creation methods 2) 1 with global access 3) 2 with guaranteed same-instance access.
What does "global access" mean to you that isn't embodied in 1)? As I see it, you declare an extern instance of 1) in a header and you have 2). global<T> is a template, so it could have a static member that could be initialized in a header, but then you could only have one. I'm confused. _____ Rob Stewart robert.stewart@sig.com Software Engineer, Core Software using std::disclaimer; Susquehanna International Group, LLP http://www.sig.com IMPORTANT: The information contained in this email and/or its attachments is confidential. If you are not the intended recipient, please notify the sender immediately by reply and immediately delete this message and all its attachments. Any review, use, reproduction, disclosure or dissemination of this message or any attachment by an unintended recipient is strictly prohibited. Neither this message nor any attachment is intended as or should be construed as an offer, solicitation or recommendation to buy or sell any security or other financial instrument. Neither the sender, his or her employer nor any of their respective affiliates makes any warranties as to the completeness or accuracy of any of the information contained herein or that this message or any of its attachments is free of viruses.

For what it's worth I faced the issue of singletons in the serialization library. I wanted a system which didn't require dragging in a multi-threaded library but I also wanted a system which would be thread-safe. I looked around quite a bit. Just at that time, a singleton library was accepted for review.
From what I remember it was much more complete, documentation, examples, addressing of thread issues etc. I resolved to wait to see if that library was accepted. It was not accepted.
I made a singleton library along the lines of that being suggested here. That library can be found in the documentation for the serialization library. The implemenation is a template which generates a singleton from any given class. It has two accessor functions: T & get_instance() and const T & get_const_instance() My ideas was that if one wanted in add thread locking somewhere it could well be in the class T. In any case, since all my usages were constructed before main is called and then there was no locking required. (I tweaked the library to achieve this). So this worked well for me. Header only and very useful. But for one fly in the ointment. If a singleton is used inside a DLL, the constructor is invoked when the dll is loaded. If the DLL is loaded explicitly with something like "LoadDLL" from multiple threads then it would be a problem. Also, the "singleton" aspect is local to the execution module. That is, if the singleton is used in both the DLL and the main module there are two "singletons" created - so they're really not singletons any more. Maybe they have to be called "moduletons". Anyway just wanted to illustrate their is a lot of history/bagage/whatever associated with this topic and it's not going to be easy to reach a concensus on something like this. Robert Ramey

On 27/01/2010, at 8:44 AM, Frank Mori Hess wrote:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1
On Tuesday 26 January 2010, GMan wrote:
Take your best singleton class, but remove the bit where it intrudes and forces only a single instantiation. Call this "global", which provides the same thing as a singleton but allows other instantiations of the class. My argument was that this class is more worth boost's time than the singleton class. The reason being, users of global could always re-introduce the single-instantiation behavior, but don't have to. This provides more flexibility.
If you peel off the singleton aspect of singletons, you're left with global state and lazy initialization. A facility that supports thread-safe lazy initialization might be useful, but why tie it to global state (which is of more dubious value)?
Sometimes the globalness and the lazy initialization are inextricably tied together. Though see rarely any benefit in enforced singletons. If it really is a singleton, then lock a global resource, like a file on an in-memory filesystem (like /dev/shm/clunky_database_lock). Much more robust and conceptually simple. (Singletons can be defeated just by running two copies of a program.) A practically useful (ie very low overhead, safe and uncomplicated) singleton design I've used is the following: struct X { }; /** Get the single instance of x */ inline X& get_x() { static X* x = NULL; if ( unlikely(!x) ) x = new X(); return *x; } // ensure the object has been initialized before main was called namespace { struct X_maker { X_maker() { get_x(); } }; X_maker X_maker_instance; } It has the following benefits: - No race conditions (see limitations though) - Lock-free, inlined, optimizable code (no memory fences or volatiles) - The code is easy to understand - Solves the static initialization order fiasco - No hairy destruction order problems It has the following limitations: - You need the OS to reclaim your object's resources on app close, the destructor is not called. - Do not spawn any threads before main, or you will lose the thread safety. Luckily, my operating system does close file descriptors, sockets, and deallocates memory, so in the real world, this works very well indeed. I never have any evil static destruction races where a static object logs a message to a singleton logger that has been already destroyed by a "too-clever-by-half" singleton implementation, causing unreproducible segfaults. My 5c, Matthew

Frank Mori Hess a écrit :
One of the motivations for the singleton pattern is making it impossible to instantiate more than one instance of the class, which something which is unintrusive cannot accomplish. Maybe I'm missing something however, as I don't see the point of boost::global<T> at all?
I spoke too quickly (in truth, I don't care about singletons, so I didn't pay too much attention). Both approaches have their merits. In any case the difference isn't just a matter of taste.

One requires creating a new tailored object, the other adapts itself to any object un-intrusively.
So it's pretty obvious global<int>.get() is better, and not just a matter of taste.
Let us discuss that: 1) Boost::global example: typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int 2) Boost::Singleton example: typedef boost::Singleton<int> global_Int; global_Int::Instance() = 5; I really do not understand the appreciable advantage of the 1) over the 2) and vice versa.:confused: The only thing I could say is that "get" is shorter word than "Instance", isn't it? -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27324932.html Sent from the Boost - Dev mailing list archive at Nabble.com.

Andrew Chinkoff <achinkoff@gmail.com> wrote:
1) Boost::global example:
typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int
2) Boost::Singleton example:
typedef boost::Singleton<int> global_Int; global_Int::Instance() = 5;
I really do not understand the appreciable advantage of the 1) over the 2) and vice versa.:confused: The only thing I could say is that "get" is shorter word than "Instance", isn't it?
Do you not see your implementation of singleton cannot, with its intrusive nature, make a global int? Fair enough it's highly unlikely you'll ever need a global POD, but like I said to Robert, a global utility *could* do it, and it could also be a singleton if desired.

GMan-6 wrote:
Personally, I don't feel Boost needs a singleton utility. Singletons themselves aren't *really* ever required. (When have you *actually* required you *cannot* make more than one?) If you don't need more than one, don't make more than one. A singleton takes this idea and forces you to mutilate your class to fulfill some silly requirement.
Perhaps some boost::global<T> utility would be better, but a singleton itself is bad practice, in my opinion. boost::global<T> would merely create a global access point to T:
typedef boost::global<int> global_Int; global_int.get() = 5; // getting the global int
It could have policies, to get the advantages of a singleton without the unnecessarily intrusive nature of a singleton. Lazy initialization, thread-safety, etc.
Hi, I don't like your global class as it could let you think you are working with two different global variable when you are working with the same. Let me show //file 1 typedef boost::global<int> my_global_Int; //file 2 typedef boost::global<int> your_global_Int; my_global_int.get() is the same as your_global_Int.get() Vicente -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27325934.html Sent from the Boost - Dev mailing list archive at Nabble.com.

That's what I came in the final of my singleton experience: 1) main.cpp - boost::Singleton demo ( http://old.nabble.com/file/p27330132/main.cpp main.cpp ); 2) singleton.hpp - boost::Singleton impl ( http://old.nabble.com/file/p27330132/singleton.hpp singleton.hpp ). Questions to Boost.Commutity: 1) Could I use that singleton implementation in my personal practice and rely it on? 2) Is it "thread safe" and "lazy initialized"? Many thanks to all who have discussed this topic!! -- View this message in context: http://old.nabble.com/-Boost.utility--tp27309940p27330132.html Sent from the Boost - Dev mailing list archive at Nabble.com.
participants (14)
-
Andrew Chinkoff
-
Frank Mori Hess
-
GMan
-
Jeff Flinn
-
Lars Viklund
-
Mathias Gaunard
-
Matthew Herrmann
-
Patrick Horgan
-
Robert Ramey
-
Steven Watanabe
-
Stewart, Robert
-
Thomas Klimpel
-
Vicente Botet Escriba
-
vicente.botet