473,661 Members | 2,431 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 1381
"SQL_Learne r" <SQ********@dis cussions.micros oft.comwrote in message
news:66******** *************** ***********@mic rosoft.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_Learne r" <SQ********@dis cussions.micros oft.comwrote in message
news:83******** *************** ***********@mic rosoft.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(vo id)
{
if (g_Key == NULL)
{
static CriticalSection cs(L"CKey::GetK ey");

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_Learne r" <SQ********@dis cussions.micros oft.comwrote in message
news:8A******** *************** ***********@mic rosoft.com...
Here is the function
CKey* CKey::GetKey(vo id)
{
if (g_Key == NULL)
{
static CriticalSection cs(L"CKey::GetK ey");

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********@dis cussions.micros oft.comwrote:
>Here is the function
CKey* CKey::GetKey(vo id)
{
if (g_Key == NULL)
{
static CriticalSection cs(L"CKey::GetK ey");

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

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

Similar topics

4
6641
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 potential problems for thread-safety. So far, I'm only confused. I need a proper explanation for the concept so I can understand how to write thread-safe functions in the future. My apologies for posting a long routine.
9
2082
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 for web servers. These apps' re tested with a stress test. That doesn' t work for my module. I searched the web but didn' t find a solution that satisfies me. I think that thread safety errors don' t occur reproduceable and so they' re hard to test and...
4
2786
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 operations?
22
37723
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() However, this throws and error: System.Threading.ThreadStateException: Thread is running or terminated; it can not restart.
4
2552
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 as a single application. I was wondering if there is a "Thread-Safety Analysis Wizard"? I'm sure I'm grossly off-base with the following, so I'm prepared to be embarrassed. Please point me in the right direction!
6
3134
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 to the client. Before adding data to the arraylist, I check if the depth of the arraylist is longer than iMaxQueueDepth, and if it is, I clear the arraylist. Is it possible that while I am clearing the arraylist, the ThreadMain at the same time...
7
1996
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
3583
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
4047
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; log.stream(INFO) << "this is an info message" << std::endl;
13
11449
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
8432
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
8343
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
8855
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
7364
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
6185
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
4179
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
4346
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1986
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1743
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.