473,898 Members | 1,946 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

A real threaded singleton

In the stuff I've read about multi threaded singleton it seems to
assume that creating the Lock is atomic, and various sources,
including Sutter go for RAII.
{
Lock l;
if ( ! inst )....
}
But I don't see how to do this with a real O/S API.
The ones I've looked at have a two step process to making a lock, they
require a "Create" function and a "Start Locking" function.

A Lock class is presumably implemented as something like:
class Lock
{
private :
PrimitiveLockTy pe PrimitiveLock;
PrimitiveHandle handle;
public:
Lock() {
PrimitiveLock = CreatePrimitive Lock():
handle = StartLocking (PrimitiveLock) ;
}
~Lock()
{
StopLocking(han dle);
KillPrimitiveLo ck(PrimitiveLoc k);
}

};

Now if I have two threads there is a chance (albeit a small one) that
I end up creating two PrimitiveLocks

Thus far, I've got around it by making the PrimitiveLock a global
static like the Instance member.
That makes error handling awkward, though if this is failing at such
an early stage then the program's not likely to work anyway.
What am I missing ?


}

Apr 9 '07 #1
2 1934

<Ev********@goo glemail.comwrot e in message
news:11******** *************@n 76g2000hsh.goog legroups.com...
In the stuff I've read about multi threaded singleton it seems to
assume that creating the Lock is atomic, and various sources,
including Sutter go for RAII.
There is a solution for a thread-safe version of that here:

http://groups.google.com/group/comp....da701564880ab4

http://appcore.home.comcast.net/vzdo...c/static-init/

http://appcore.home.comcast.net/vzoom/refcount/

You use a hashed-mutex/spinlock scheme to handle atomic lock
construction/destruction. e.g.:

// Details
#define DETAIL_CONCATX( __t1, __t2)__t1##__t2
#define DETAIL_CONCAT(_ _t1, __t2)CONCATX(__ t1, __t2)

#define DETAIL_HASHMUTE X_8(__init)\
__init, __init, __init, __init, __init, __init, __init, __init

#define DETAIL_HASHMUTE X_32(__init)\
DETAIL_HASHMUTE X_8(__init), DETAIL_HASHMUTE X_8(__init),\
DETAIL_HASHMUTE X_8(__init), DETAIL_HASHMUTE X_8(__init)

#define DETAIL_HASHMUTE X_128(__init)\
DETAIL_HASHMUTE X_32(__init), DETAIL_HASHMUTE X_32(__init),\
DETAIL_HASHMUTE X_32(__init), DETAIL_HASHMUTE X_32(__init)

#define DETAIL_HASHMUTE X_256(__init)\
DETAIL_HASHMUTE X_128(__init), DETAIL_HASHMUTE X_128(__init)

#define DETAIL_HASHMUTE X_512(__init)\
DETAIL_HASHMUTE X_256(__init), DETAIL_HASHMUTE X_256(__init)

#define DETAIL_HASHMUTE X_CONCAT(__init , __count)\
DETAIL_CONCAT(D ETAIL_HASHMUTEX _, __count)(__init )
// Impl
#include <pthread.h>

#define HASHMUTEX_DEPTH () 256
#define HASHMUTEX_INITI ALIZER() PTHREAD_MUTEX_I NITIALIZER

#define HASHMUTEX_PTR(_ _ptr) (((int)__ptr) % HASHMUTEX_DEPTH ())

#define HASHMUTEX_STATI CINIT() {\
DETAIL_HASHMUTE X_CONCAT(HASHMU TEX_INITIALIZER (), HASHMUTEX_DEPTH ())\
}

// hashed-mutex table
static pthread_mutex_t hashmutex_table[
HASHMUTEX_DEPTH ()
] = HASHMUTEX_STATI CINIT();

static int hashmutex_lock( void* const ptr) {
return pthread_mutex_l ock(&hashmutex_ table[HASHMUTEX_PTR(p tr)]);
}

static int hashmutex_trylo ck(void* const ptr) {
return pthread_mutex_t rylock(&hashmut ex_table[HASHMUTEX_PTR(p tr)]);
}

static int hashmutex_unloc k(void* const ptr) {
return pthread_mutex_u nlock(&hashmute x_table[HASHMUTEX_PTR(p tr)]);
}


class A {};
class B {};

static A g_a;
static B g_b;
int main() {
// lock & unlock a
hashmutex_lock( &g_a);
// ...
hashmutex_unloc k(&g_a);

// lock & unlock b
hashmutex_lock( &g_b);
// ...
hashmutex_unloc k(&g_b);
return 0;
}

Got to watch out for deadlocks... Here is one possible solution:

http://groups.google.com/group/comp....011baf08844c4/

Any thoughts?
:^)

Apr 9 '07 #2
On Apr 9, 7:23 pm, EvilOld...@goog lemail.com wrote:
In the stuff I've read about multi threaded singleton it seems to
assume that creating the Lock is atomic, and various sources,
including Sutter go for RAII.
{
Lock l;
if ( ! inst )....}
But I don't see how to do this with a real O/S API.
The ones I've looked at have a two step process to making a lock, they
require a "Create" function and a "Start Locking" function.
Any real answer will depend on the OS. Normally, you should be
able to create and initialize a mutex as a static object. If
not, you need a global mutex, which is used to synchronize the
creation of all of the secondary mutexes, and some tricky way of
initializing it.

In my own code, I generally find it acceptable to require that
threads don't start until after entering main, which means in
practice that the initialization of objects with static
lifetime, at least those which aren't in a dynamically linked
object, has occured. Thus, if you use a singleton, all you have
to do to ensure that it doesn't need a lock is to ensure that at
least one call to the instance function occurs during static
initialization. Something like:

bool dummyForInitial ization = Singleton::inst ance(), tru ;

does the trick, as does:

Singleton* Singleton::ourI nstance = &Singleton::ins tance() ;
A Lock class is presumably implemented as something like:
class Lock
{
private :
PrimitiveLockTy pe PrimitiveLock;
PrimitiveHandle handle;
public:
Lock() {
PrimitiveLock = CreatePrimitive Lock():
handle = StartLocking (PrimitiveLock) ;}
~Lock()
{
StopLocking(han dle);
KillPrimitiveLo ck(PrimitiveLoc k);
}
};
No. An RAII "lock" class is always based on an external mutex
or some other external synchronization primitive. You still
have the problem of creating that external object, of course.
Now if I have two threads there is a chance (albeit a small one) that
I end up creating two PrimitiveLocks
Thus far, I've got around it by making the PrimitiveLock a global
static like the Instance member.
That's normally what you do.
That makes error handling awkward, though if this is failing at such
an early stage then the program's not likely to work anyway.
If creating the lock fails, you have a problem. As you say, it
occurs at such an early stage that the program isn't likely to
work anyway, so you just abort with an error message.

--
James Kanze (GABI Software) email:ja******* **@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientier ter Datenverarbeitu ng
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34

Apr 10 '07 #3

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

Similar topics

18
12610
by: Ken | last post by:
Hi. Can anyone refer me to any articles about the compatibility between c++ polymorphism and real-time programming? I'm currently on a real-time c++ project, and we're having a discussion about whether we should allow polymorphism. Our system is not embedded and does not need to be as real-time as, say, a pacemaker. But it does involve updating displays based on radar input. So a need for something close to real-time is desired...
2
5881
by: Sean Dettrick | last post by:
Hi, apologies for yet another Singleton posting. From reading around previous postings etc, I've cobbled together two Singleton template definitions - one that returns a reference, and one that returns a pointer. I understand the pointer one and it works, but the reference one doesn't work as I expect. Can anybody explain this to me? (Code below). I'm not really looking for thread safety or for something as general
10
2664
by: E. Robert Tisdale | last post by:
Could somebody please help me with the definition of a singleton? > cat singleton.cc class { private: // representation int A; int B; public: //functions
3
2507
by: Alicia Roberts | last post by:
Hello everyone, I have been researching the Singleton Pattern. Since the singleton pattern uses a private constructor which in turn reduces extendability, if you make the Singleton Polymorphic what sort of problems/issues should be considered? Also, I see that a singleton needs to be set up with certain data such as file name, database URL etc. What issues are involved in this, and how would you do this? If someone knows about the...
3
3934
by: Harry | last post by:
Hi ppl I have a doubt on singleton class. I am writing a program below class singleton { private: singleton(){}; public: //way 1
5
5318
by: Pelle Beckman | last post by:
Hi, I've done some progress in writing a rather simple singleton template. However, I need a smart way to pass constructor arguments via the template. I've been suggested reading "Modern C++ Design" or similar books, but I feel there are full of clever guys here who could help me out.
1
5234
by: Jim P. | last post by:
I'm having trouble returning an object from an AsyncCallback called inside a threaded infinite loop. I'm working on a Peer2Peer app that uses an AsyncCallback to rerieve the data from the remote peer. I have no problem connecting the peers and streaming Network Streams. When the incoming data is finished recieving, I act upon it. This works great as long as all of the code is inside my form. I want to build the networking code into a...
11
1920
by: John Lee | last post by:
Hi, I like the C# implemention of singleton class presented at MSDN. My question is that is it correct or right thing to do to modify that class to make the class will return the same instance if for the same parameter when calling GetInstance? public static Singleton GetInstance(string parameter) { //using a hashtable or some other type to hold the instance - parameter
9
2150
by: d.adamkiewicz | last post by:
Hello Folks Anybody can show me real world singleton class example? Something that works (is implemented) as part of working solution. Does it make sense to create database handler class that way? Regards Darek
0
9993
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
9839
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
11256
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
10481
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
9658
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
8034
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
7187
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5877
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...
2
4295
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.