473,385 Members | 1,766 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Thread Safety in C++ code


Hi,

I was going through this article
http://blogs.msdn.com/oldnewthing/ar.../08/85901.aspx
This talks about "C++ scoped static initialization is not thread-safe, on
purpose!"
One of the resolutions is to use to critical section to avoid race condition.
My question is what if in any program, critical section itself is static,
then there will be thread safety issue, any pointers/ideas how avoid this
condition?

Thanks!
Oct 10 '06 #1
11 1359
"SQL_Learner" <SQ********@discussions.microsoft.comwrote in message
news:66**********************************@microsof t.com...
I was going through this article
http://blogs.msdn.com/oldnewthing/ar.../08/85901.aspx
This talks about "C++ scoped static initialization is not thread-safe, on
purpose!"
One of the resolutions is to use to critical section to avoid race
condition.
My question is what if in any program, critical section itself is static,
then there will be thread safety issue, any pointers/ideas how avoid this
condition?
In order to synchronize between threads, a single critical section must be
shared between them. It's a wise strategy to initialize the shared critical
section before you start any subsequent threads. Then there is no issue.

Regards,
Will
Oct 10 '06 #2
In order to synchronize between threads, a single critical section must be
shared between them. It's a wise strategy to initialize the shared critical
section before you start any subsequent threads. Then there is no issue.

Regards,
Will
Hi Will,

Thanks for your response. I am little unclear about the shared critical
section. My actual problem is I have a block of code which has a critical
section which is declared as static and this looks like a probable thread
safety issue as this might create 2 copies of critical sections. I am
looking for a alternative way to avoid this.

Thanks

Oct 10 '06 #3
"SQL_Learner" <SQ********@discussions.microsoft.comwrote in message
news:83**********************************@microsof t.com...
Thanks for your response.
You are welcome.
I am little unclear about the shared critical section. My actual
problem is I have a block of code which has a critical
section which is declared as static and this looks like
a probable thread safety issue as this might create 2 copies
of critical sections. I am looking for a alternative way to avoid this.
You'll have to show a _little_ code.

Regards,
Will
Oct 10 '06 #4
You are welcome.
I am little unclear about the shared critical section. My actual
problem is I have a block of code which has a critical
section which is declared as static and this looks like
a probable thread safety issue as this might create 2 copies
of critical sections. I am looking for a alternative way to avoid this.

You'll have to show a _little_ code.

Regards,
Will
Hi Will,

Here is the function
CKey* CKey::GetKey(void)
{
if (g_Key == NULL)
{
static CriticalSection cs(L"CKey::GetKey");

AutoLock lock(cs);
if ( g_Key == NULL)
{
static CKey key;
g_Key = &key;
}
}
return g_Key;
}

Here I already have a Critical Section initialized as static. I want to
rewrite this to handle the race conditions.

Thanks
Oct 10 '06 #5
"SQL_Learner" <SQ********@discussions.microsoft.comwrote in message
news:8A**********************************@microsof t.com...
Here is the function
CKey* CKey::GetKey(void)
{
if (g_Key == NULL)
{
static CriticalSection cs(L"CKey::GetKey");

AutoLock lock(cs);
if ( g_Key == NULL)
{
static CKey key;
g_Key = &key;
}
}
return g_Key;
}

Here I already have a Critical Section initialized as static. I want to
rewrite this to handle the race conditions.
Oh, sorry. Judging by the name I guess you are using MFC or ATL, neither of
which is my forte (I much prefer the API)

Assuming that the constructor for the class initializes it, then what you
probably do is move it outside of any function. I could be wrong. If no one
pops in here with more definitive information you can post again in an MFC
or ATL group.

Regards,
Will
Oct 10 '06 #6
On Tue, 10 Oct 2006 08:14:02 -0700, SQL_Learner
<SQ********@discussions.microsoft.comwrote:
>Here is the function
CKey* CKey::GetKey(void)
{
if (g_Key == NULL)
{
static CriticalSection cs(L"CKey::GetKey");

AutoLock lock(cs);
if ( g_Key == NULL)
{
static CKey key;
g_Key = &key;
}
}
return g_Key;
}

Here I already have a Critical Section initialized as static. I want to
rewrite this to handle the race conditions.
You do have a race condition for the initialization of cs, and as Will
said, one way to fix it is to make it a global variable. (Just don't call
GetKey during initialization of some other global that is declared before
cs or in another translation unit.) Then you're just left with the issues
inherent to the "Double-Checked Locking Pattern", which you can Google for
details.

--
Doug Harrison
Visual C++ MVP
Oct 10 '06 #7
On Tue, 10 Oct 2006 14:02:58 -0500, Doug Harrison [MVP] wrote:
>>Here I already have a Critical Section initialized as static. I want to
rewrite this to handle the race conditions.

You do have a race condition for the initialization of cs, and as Will
said, one way to fix it is to make it a global variable.
Then you're just left with
the issues inherent to the "Double-Checked Locking Pattern"
Here is a good article on the failings of many DCLP implementations:

http://www.aristeia.com/Papers/DDJ_J...lp%20broken%22

Regards,

Andrew Marlow
Oct 11 '06 #8
Thanks all fro your replies.

Yes, I moved the Critical Section into global scope to avoid race condition
and I am making sure that this global is initialized only once.

Oct 12 '06 #9
SQL_Learner wrote:
Thanks all fro your replies.

Yes, I moved the Critical Section into global scope to avoid race condition
and I am making sure that this global is initialized only once.
My solution was possibly overkill. For future reference, boost has an
implementation of "call_once": http://www.boost.org/doc/html/call_once.html

Tom
Oct 12 '06 #10
Hi Tom,

The URL http://www.boost.org/doc/html/call_once.html is not working

Thanks

"Tom Widmer [VC++ MVP]" wrote:
SQL_Learner wrote:
Thanks all fro your replies.

Yes, I moved the Critical Section into global scope to avoid race condition
and I am making sure that this global is initialized only once.

My solution was possibly overkill. For future reference, boost has an
implementation of "call_once": http://www.boost.org/doc/html/call_once.html

Tom
Oct 17 '06 #11
SQL_Learner wrote:
Hi Tom,

The URL http://www.boost.org/doc/html/call_once.html is not working

Thanks
www.boost.org seems to be down, this one may help:

http://www.boost-consulting.com/download.html
Oct 18 '06 #12

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

Similar topics

4
by: Jonathan Burd | last post by:
Greetings everyone, Here is a random string generator I wrote for an application and I'm wondering about the thread-safety of this function. I was told using static and global variables cause...
9
by: Alexander Fleck | last post by:
Hi, I' ve to make a software module thread safe. I know how to realize that and what' re the main topics of thread safety. But I don' t know how thread safety can be tested. I read about a test...
4
by: The Crow | last post by:
for example i have static readonly SqlParameter and i want to clone them at runtime. as clone operation will not write to SqlParameter object, just reading, should i lock that object during read...
22
by: Brett | last post by:
I have a second thread, t2, that errors out and will stop. It's status is then "Stopped". I try to start t2 from thread 1, t1, by checking If t2.threadstate = "Stopped" Then t2.start() ...
4
by: Warren Sirota | last post by:
Hi, I've got a method that I want to execute in a multithreaded environment (it's a specialized spider. I want to run a whole bunch of copies at low priority as a service). It works well running...
6
by: fniles | last post by:
I am using VB.NET 2003 and a socket control to receive and sending data to clients. As I receive data in 1 thread, I put it into an arraylist, and then I remove the data from arraylist and send it...
7
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...
13
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?
2
by: ZHENG Zhong | last post by:
Hi, I implemented a small logging library with the API like this: logger& log = log_manager::instance().get_logger("my_logger"); log.stream(DEBUG) << "this is a debug message" << std::endl;...
13
by: Henri.Chinasque | last post by:
Hi all, I am wondering about thread safety and member variables. If I have such a class: class foo { private float m_floater = 0.0; public void bar(){ m_floater = true; }
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.