473,570 Members | 2,927 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread safe way to initialize static object

Hi I have a THREAD class that uses the static variable NextThreadID to
store the id of the next thread to be created and a static Mutex to
protect it.

class THREAD {

public:
int Start(void);
private:
unsigned int ThreadID;

// Will be coppied into ThreadID when a new thread is started
and then incremented by1
static unsigned int NextThreadID;
static MUTEX Mutex;
};

int THREAD::Start(v oid) {
// Start a new thread

Mutex.Acquire() ;
ThreadID = NextThreadID;
NextThreadID++;
Mutex.Release() ;
if (ThreadStarted)
{
return 1;
}
else
{
return 0;
}

}

At the moment I initialize NextThreadID and Mutex before main() and set
it equal to zero. Is there a cleaner way to initalize these objects?
Obviously I cant do it in the THREAD object itself because several
threads may try to initalize the same object at the same time.

I have read
http://www-d0.fnal.gov/KAI/doc/tutor...alization.html
which kind of explains what I am trying to.
extern unsigned int THREAD::NextThr eadID;
extern MUTEX THREAD::Mutex;
class nifty_counter {
static int count;
public:
nifty_counter()
{
if (count++ == 0) {
// initialize the NextThreadID and its protector
Mutex
THREAD::NextThr eadID = 0;
THREAD::Mutex;
}
}
~nifty_counter( )
{
if (--count == 0) {
// clean up obj1 ... objn
}
}
};

//Now every file that includes the library header also creates
a nifty_counter object and initializes it with the effect of increasing
nifty_counter
static nifty_counter nifty;

However even if i declare the nifty class a friend of the THREAD class
I get the compile time error that THREAD::Mutex and
THREAD::NextThr eadID member cannot be declared here.

May 14 '06 #1
1 4227
philwozza wrote:
Hi I have a THREAD class that uses the static variable NextThreadID to
store the id of the next thread to be created and a static Mutex to
protect it.


This question is really not related to threads. It is simply about
static initialization. You need to create a separare cpp file that
contains the static definitions. e.g.

//header file
struct foo
{
static int bar;
};

//cpp file
int foo::bar = 2; // initialization by constant expression

This kind of "POD" initialization happens before the code starts execution.

This type of static initialization is alot trickier.

int foo( int initializer )
{
static int var = initializer;
return var ++;
}

Some compilers will provide a thread-safe static initialization (gcc4.x)
and other compilers may initialize var more than once because of a race
condition in the generated code for the static initialization.
May 14 '06 #2

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

Similar topics

2
6883
by: Steve | last post by:
Is a static method that uses local variables thread safe (eg in a web service) In the following code assuming GetRandomValue() and DoSomethingElse() are thread safe, is the static method thread safe public class Cach public static int GetAValue( int x = 0 x = GetRandomValue()
15
5397
by: Mountain Bikn' Guy | last post by:
Is the second version shown below better? I couldn't locate enough info about in order to tell. 1.. My commonly used singleton pattern implementation looks like this (it was inspired by Eric Gunnerson's book): private static volatile MyClass singleton = null; private static object sync = new object();//for static lock public static...
6
8296
by: GG | last post by:
Is this public static method thread safe. //Receives a file name as a parameter //and returns the contents of that file as a string public static string FileToStr(string fileName) { FileStream fStream=null; lock(fStream) //just in case we use it for multithreading to be thread safe {
7
2295
by: Chad Zalkin | last post by:
We are evaluating some old code that was written as part of our math library. This code uses some optimizations that I'm not sure are necessary or safe, but is a source of debate between my coworkers. Method 1 includes a temporary storage varriable at class scope. Method 2 includes a temporary storage varriable at method scope. Method 3...
8
2006
by: Senna | last post by:
Hi I have some questions about this code, http://code.doria.se/?c=18. 1. Will the Adapter class be thread-safe? 2. In the #region Way 1 I use lock(_lockobj) every time I go about and do something, is this necessary? 3. If the answer in question 2 is no, when are one suppose to use lock()? Or
5
3783
by: admin | last post by:
ok This is my main. Pretty much it goes through each category and starts up 4 worker threads that then ask for groups to gether from. My problem is that when the thread gets done it keeps the mysql connections open so I end up with quite a few at the end. Is there a different way that I should do this? class Program { static string...
7
1993
by: intrader | last post by:
I have the following small classes: //----------------code--------------- using System; using System.Collections.Generic; using System.Text; namespace ValidatorsLibrary { public class ValidatorBase {
13
3568
by: arun.darra | last post by:
Are the following thread safe: 1. Assuming Object is any simple object Object* fn() { Object *p = new Object(); return p; } 2. is return by value thread safe?
0
204
by: Anthony Williams | last post by:
James Kanze <james.kanze@gmail.comwrites: 6.7/4 of the C++ Standard describes initialization of local objects with static storage duration: "The zero-initialization (8.5) of all local objects with static storage duration (3.7.1) is performed before any other initialization takes place. A local object of POD type (3.9) with static...
0
7950
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. ...
0
8151
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...
1
7702
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8000
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...
0
5247
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...
0
3684
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...
0
3671
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2133
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
1
1238
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.