473,770 Members | 2,144 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 4244
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
6902
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
5409
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 MyClass Instance {
6
8304
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
2308
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 includes a temporary static storage varriable at method scope. Are any of the methods better than...
8
2018
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
3806
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 categories = { "emulation" , "audio" , "console" , "anime" , "xxx" , "tv" , "pictures" , "video" };
7
2003
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
3610
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 storage duration initialized with constant-expressions is
0
9454
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,...
1
10038
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
9906
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...
1
7456
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
6712
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
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
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
2
3609
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.