473,805 Members | 2,008 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

singleton with multithreading

ank
Hi,
I have some question about Singleton Pattern in C++.

I think I understand that static initialization order across
translation unit
is unspecified by the standard, but what can I do to ensure that some
kind of
static mutex is automatically initialized before the first use of it?

I cannot assume that this mutex is used only after executing main()
function because I need to use this mutex to lock singleton inside
initialization code and may apply double-check pattern.

Currently, I have very little experience with multithread programming.
I am not a native English speaker so my message may not be well
written.

Thanks in advance for any suggestions.

Jul 23 '05 #1
6 3055
On Sun, 26 Jun 2005 13:00:41 +0400, ank <ek************ *******@gmail.c om>
wrote:
Hi,
I have some question about Singleton Pattern in C++.

I think I understand that static initialization order across
translation unit
is unspecified by the standard, but what can I do to ensure that some
kind of
static mutex is automatically initialized before the first use of it?


To force initialization without dependency on module initialization order
you may employ schwarz counter idiom (google groups for it). This is how
standard streams (std::cout, etc) get initialized.

--
Maxim Yegorushkin
<fi************ ****@gmail.com>
Jul 23 '05 #2
ank
Which means I have to include the initialization code in every module
that
use my service.
Am I right?

Jul 23 '05 #3
On Sun, 26 Jun 2005 13:26:30 +0400, ank <ek************ *******@gmail.c om>
wrote:
Which means I have to include the initialization code in every module
that use my service.
Am I right?


Only the code that calls your initialization code at the proper moment.
The initialization code can be in any translation unit you like.

--
Maxim Yegorushkin
<fi************ ****@gmail.com>
Jul 23 '05 #4
ank
Maxim Yegorushkin wrote:

Only the code that calls your initialization code at the proper moment.
The initialization code can be in any translation unit you like.

--
Maxim Yegorushkin
<fi************ ****@gmail.com>


Thanks for your suggestion Maxim, I think it is the reasonable thing to
do to deal with the problem.

I think I can use the counter to help initialize mutex before any code
that acquire lock with it and all is done, in thread-safe fashion.
This technique don't suffer from threading issue because you have no
way use the object before the counter is initialized, by any
global/static external object, in any thread, right?.

Is Schwarz counter efficient enough
or is it best to use non-portable compiler option?
I want to know other's opinion.

Jul 23 '05 #5
On Sun, 26 Jun 2005 14:31:38 +0400, ank <ek************ *******@gmail.c om>
wrote:
Maxim Yegorushkin wrote:

Only the code that calls your initialization code at the proper moment.
The initialization code can be in any translation unit you like.

[]
I think I can use the counter to help initialize mutex before any code
that acquire lock with it and all is done, in thread-safe fashion.
This technique don't suffer from threading issue because you have no
way use the object before the counter is initialized, by any
global/static external object, in any thread, right?.


Right. By the time you use it it has already been initialized.

--
Maxim Yegorushkin
<fi************ ****@gmail.com>
Jul 23 '05 #6
ank wrote:
Hi,
I have some question about Singleton Pattern in C++.

I think I understand that static initialization order across
translation unit
is unspecified by the standard, but what can I do to ensure that some
kind of
static mutex is automatically initialized before the first use of it?

I cannot assume that this mutex is used only after executing main()
function because I need to use this mutex to lock singleton inside
initialization code and may apply double-check pattern.

Currently, I have very little experience with multithread programming.
I am not a native English speaker so my message may not be well
written.

Thanks in advance for any suggestions.


Well for starts, read this
http://www.cs.umd.edu/~pugh/java/mem...edLocking.html
This may kick off one of those interminable discussions where about half
of the participants will never get it.

To summarize, DCL isn't actually broken, it just that there aren't any
portable mechanisms to implement it correctly on all platforms. The
naive implementation using pointers assumes dependent load ordering. You
have to know which platforms this works on. It doesn't work on Alpha
processors.

There are design patterns let you implement DCL correctly. One is to have
each thread use a thread local variable whether it has a properly synchronized
view of the singleton data. The other is to only access the singleton via
a object of that class which has been properly synchronized with the singleton
in its construction. Access to the objects is assumed to be properly synchronized
also.

Initialization of a Posix pthread mutex is
pthread_mutex_t mutex = PTHREAD_MUTEX_I NITIALIZER;

For windows you can use a named Mutex which can be dynamically initialized in
a thread-safe manner. Windows CriticalSection initialization isn't thread-safe.
You can use compare and swap to initialize a CriticalSection . Example of this
here in the initFreeQueue subroutine. It also uses the access via object technique.
http://groups.google.com/groups?q=g:...6%40xemaps.com
I'd stay away of any naive spinlock implementations . Not only are they inefficient but
they're likely to be incorrect with regard to proper memory visibility, i.e. missing
necessary memory barriers.


--
Joe Seigh

When you get lemons, you make lemonade.
When you get hardware, you make software.
Jul 23 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

18
2122
by: Alfonso Morra | last post by:
Hi, Anyone knows of a link to a singleton design pattern example in C++ (preferably not using a global variable?).
8
3971
by: Robert Zurer | last post by:
I have a server application that makes a MarshalByReferenceObject available via remoting. It's lifetime is set to never expire and it is implemented as a Singleton. Are calls to this object inherently thread safe? If 1000 threads all call the same method of this object at once, do I have to add anything to my code to assure that there are no problems? Excuse me if this is really obvious. I am somewhat new to remoting and totally new...
1
1095
by: Francois Malgreve | last post by:
Hi, I am implemeting a singleton object in my ASP.NET application. Therefore I need to know if ASP.NET is multithreaded or not. All i know is that there is one worker process running ASP.NET application (aspnet_wp). That process being called by IIS. Nevertheless I do not know much more than that. And I do not know if this process will launch several threads or not. I assume it could have a pool of thread to process different request...
15
3058
by: Nick Keighley | last post by:
Hi, I found this in code I was maintaining template <class SingletonClass> SingletonClass* Singleton<SingletonClass>::instance () { static SingletonClass _instance; return &_instance; }
2
2060
by: keepyourstupidspam | last post by:
Hi, I am wondering if My Singleton class is ok from a thread safety point of view. Am i adding the thread locks in the right places? template <typename T> class DLLEXPORT CSingleton
6
3198
by: toton | last post by:
Hi, If I have a singleton class based on dynamic initialization (with new ) , is it considered a memory leak? Anything in C++ standard says about it ? And little off - topic question , If the singleton is initialized as a static variable , it seems there is some threading issue . Is it the issue during singleton initialization only , or during the access also? If the singleton is per thread basis (then no more singleton though ), and...
3
18258
weaknessforcats
by: weaknessforcats | last post by:
Design Pattern: The Singleton Overview Use the Singleton Design Pattern when you want to have only one instance of a class. This single instance must have a single global point of access. That is, regardless of where the object is hidden, everyone needs access to it. The global point of access is the object's Instance() method. Individual users need to be prevented from creating their own instances of the Singleton.
1
4401
by: tlann | last post by:
I'm getting errors about a singleton when I put it into a dll. The dll compiles without any problems. However, when I try to link it to another dll I get the following error. libFoo-Bar error LNK2001: unresolved external symbol "private: static class MSGTMS:ObjectManager * MSGTMS::ObjectPostManager::m_instance" (?m_instance@ObjectManager@MSGTMS@@0PAV12@A) The Singleton class looks like this #define LIBMSGTM_Managers_EXPORT...
3
2293
by: Bob Doe | last post by:
Hello, how to I replace singleton classes using function scope static variables with one that doesn't use function scope static variables?: class Foo { public: static Foo &instance(); virtual ~Foo(); ...
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10613
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10363
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10107
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.