473,756 Members | 4,046 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Temporary varriables and thread safety

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 the others in terms of speed and
thread safety?
I don't believe method 1 or 3 are thread safe, but I think method 2 may
be too slow for a high-performance library. Is there a method 4 that
we should evaluate?

As an aside, I can't find in the standard where static is addressed in
terms of a member function. Is it true that a static varriable within
a member function exists for all instances?

/// ---- method 1

class vector {
....
private:
vector tempVector;
};
vector::somefun ction() {
// writes to tempVector as temporary storage
}
/// ---- method 2
class vector {
....
};
vector::somefun ction() {
vector tempVector;
// writes to tempVector as temporary storage
}

/// --- method 3
class vector {
....
};
vector::somefun ction() {
static vector tempVector;
// writes to tempVector as temporary storage
}

Jan 13 '06 #1
7 2307
Chad Zalkin wrote:
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 the others in terms of speed and
thread safety?
This question is _better_ asked in a newsgroup that actually deals with
threading: comp.programmin g.threads. C++ does not have support, not does
it have any definitions of, threading. The program is assumed to be
single-threaded in C++ standard.

Now, when talking about threads it is essential to identify the data that
can be changed. You didn't say how many threads are accessing what part
of data at some point.
I don't believe method 1 or 3 are thread safe, but I think method 2 may
be too slow for a high-performance library. Is there a method 4 that
we should evaluate?

As an aside, I can't find in the standard where static is addressed in
terms of a member function. Is it true that a static varriable within
a member function exists for all instances?
A static object is a static object regardless of what scope it's in. It's
essentially a singleton.
/// ---- method 1

class vector {
...
private:
vector tempVector;
You simply _physically_ cannot have an object that contains an instance of
its own type.
};
vector::somefun ction() {
Does this one have any return value type?
// writes to tempVector as temporary storage
It is generally _unknown_ here what storage duration 'tempVector' has,
since its storage duration is the same as that of '*this' object. (All
that assuming that the type of 'tempVector' is _not_ the same as the
object that contains it)
}
/// ---- method 2
class vector {
...
};
vector::somefun ction() {
vector tempVector;
// writes to tempVector as temporary storage
This is the most "thread-safe", largely because in many threading models
(if not all), automatic variables are "per-thread".
}

/// --- method 3
class vector {
...
};
vector::somefun ction() {
static vector tempVector;
// writes to tempVector as temporary storage
This is the _least_ "thread-safe", since static objects are usually shared
between all threads.
}


To sum up: method 2 is generally thread-safe, method 3 is generally not,
and nothing can be said about method 1.
V
Jan 13 '06 #2
Chad Zalkin wrote:
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 the others in terms of speed and
thread safety?
I don't believe method 1 or 3 are thread safe, but I think method 2 may
be too slow for a high-performance library. Is there a method 4 that
we should evaluate?


What makes you think that accessing a variable at local scope is slower
than that at class scope?

The narrower the scope the easier it is for the compiler to optimise.

If there is no requirement for the temporary variable to have scope
outside of a function, don't do it. Declare objects as late as
possible, and with the narrowest scope possible.

Be sure to use initialisation rather than assignment wherever possible.
If the object has a constructor, use an initialisation list. When
instantiating the object, use initialisation rather than default
construction and assignment.

You haven't really described how this temporary object is actually
initialised, how it is used, and why you think it is an optimisation
technique.

I mean, what is the alternative that you suppose is slower?

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Jan 13 '06 #3
Victor Bazarov wrote:
/// ---- method 1

class vector {
...
private:
vector tempVector;


You simply _physically_ cannot have an object that contains an instance of
its own type.
};


Yes, but one could use a pointer for tempVector.
If the class vector contains other dynamically allocated members,
this might be a performance improvement over method 2
(assuming that each thread maintains its own instance of vector).

Stephan

Jan 13 '06 #4
Chad Zalkin wrote:
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 the others in terms of speed and
thread safety?
I don't believe method 1 or 3 are thread safe, but I think method 2 may
be too slow for a high-performance library. Is there a method 4 that
we should evaluate?


In theory you might require that the thread provides the temp. vector
(in analogy to localtime, localtime_r)

vector::somefun ction(vector& tempVector);

However this will only be useful if the tempory vector is used outside
the class vector and not an implementation detail of
vector::somefun ction().

Regards, Stephan
br****@osb-systems.com
Open source rating and billing engine for communication networks.

Jan 13 '06 #5

Victor Bazarov wrote:
Chad Zalkin wrote:
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 the others in terms of speed and
thread safety?


This question is _better_ asked in a newsgroup that actually deals with
threading: comp.programmin g.threads. C++ does not have support, not does
it have any definitions of, threading. The program is assumed to be
single-threaded in C++ standard.

Now, when talking about threads it is essential to identify the data that
can be changed. You didn't say how many threads are accessing what part
of data at some point.
I don't believe method 1 or 3 are thread safe, but I think method 2 may
be too slow for a high-performance library. Is there a method 4 that
we should evaluate?

As an aside, I can't find in the standard where static is addressed in
terms of a member function. Is it true that a static varriable within
a member function exists for all instances?


A static object is a static object regardless of what scope it's in. It's
essentially a singleton.
/// ---- method 1

class vector {
...
private:
vector tempVector;


You simply _physically_ cannot have an object that contains an instance of
its own type.
};
vector::somefun ction() {


Does this one have any return value type?
// writes to tempVector as temporary storage


It is generally _unknown_ here what storage duration 'tempVector' has,
since its storage duration is the same as that of '*this' object. (All
that assuming that the type of 'tempVector' is _not_ the same as the
object that contains it)
}
/// ---- method 2
class vector {
...
};
vector::somefun ction() {
vector tempVector;
// writes to tempVector as temporary storage


This is the most "thread-safe", largely because in many threading models
(if not all), automatic variables are "per-thread".
}

/// --- method 3
class vector {
...
};
vector::somefun ction() {
static vector tempVector;
// writes to tempVector as temporary storage


This is the _least_ "thread-safe", since static objects are usually shared
between all threads.
}


To sum up: method 2 is generally thread-safe, method 3 is generally not,
and nothing can be said about method 1.
V

In defence of my own sanity, method 1 was not meant to include itself.
Let's all imagine that the tempVector is now of type foo in all
methods.

The part that I forgot to mention in my haste was that more than one
method will use the temporary storage:
class vector {
void add(); // needs temporary storage
void sub(); // needs temporary storage
void dot(); // needs temporary storage
};

class tempStorage
{
public:
// some data members
};

Now, let's ignore the threadding issue since it is OT.

If add(), sub(), and dot() all need to store some temporary data during
their runtime,
is it more efficient to store this data at class level (constructing
and destructing once per object) or at function level (constructing and
destructing once per function call; potentially many more times).

Since add(), sub(), and dot() do not call each other, storing the data
at class level becomes possible. (But then the thread issue comes into
play...)

What are the pro's and con's of scoping at each level? What can I
trust the compiler to be allowed to optimize? What can I do to help
the compiler optimize?
Thanks for any insight!

Jan 13 '06 #6
Chad Zalkin wrote:
In defence of my own sanity, method 1 was not meant to include itself.
Let's all imagine that the tempVector is now of type foo in all
methods.

The part that I forgot to mention in my haste was that more than one
method will use the temporary storage:
class vector {
void add(); // needs temporary storage
void sub(); // needs temporary storage
void dot(); // needs temporary storage
};

class tempStorage
{
public:
// some data members
};

Now, let's ignore the threadding issue since it is OT.

If add(), sub(), and dot() all need to store some temporary data during
their runtime,
is it more efficient to store this data at class level (constructing
and destructing once per object) or at function level (constructing and
destructing once per function call; potentially many more times).
Well, you forgot something:

Class level: Contruction once. Assignment for each function call.
Function level: Construct & initialisation once per call.
Since add(), sub(), and dot() do not call each other, storing the data
at class level becomes possible. (But then the thread issue comes into
play...)
Indeed. And although you don't need to construct the object, you do
need to assign to it, which may or may not be faster than constructing
and initialising.

Don't forget that it's in automatic storage, not heap... so the memory
is already "allocated" .
What are the pro's and con's of scoping at each level? What can I
trust the compiler to be allowed to optimize? What can I do to help
the compiler optimize?


As I said, declare variables as late as possible and in as narrow scope
as possible, prefer initialisation to assignment.

Not only do you help the compiler optimise, by narrowing what it has to
look at, but you also fix thread issues.

The only way you'll know if this works in your situation is by profiling.

Ben Pope
--
I'm not just a number. To many, I'm known as a string...
Jan 13 '06 #7
Chad Zalkin wrote:
[..]
Let's all imagine that the tempVector is now of type foo in all
methods.

The part that I forgot to mention in my haste was that more than one
method will use the temporary storage:
class vector {
void add(); // needs temporary storage
void sub(); // needs temporary storage
void dot(); // needs temporary storage
};

class tempStorage
{
public:
// some data members
};

Now, let's ignore the threadding issue since it is OT.

If add(), sub(), and dot() all need to store some temporary data during
their runtime,
is it more efficient to store this data at class level (constructing
and destructing once per object) or at function level (constructing and
destructing once per function call; potentially many more times).
<triallawyer>
Objection: leading!
</triallawyer>

It all depends on how much it takes to construct that object and how big
it actually is. You are forgetting an important element of performance:
make your objects smaller. If you store anything at the object level, you
make it bigger. It may not have effect on the performance in this
particular area of your program, but somewhere else... Which leads me to
another point: do not attempt to optimize before you have a chance to
measure the performance and conclude _whether_ and _where_ the actual
optimization is needed.
Since add(), sub(), and dot() do not call each other, storing the data
at class level becomes possible. (But then the thread issue comes into
play...)

What are the pro's and con's of scoping at each level? What can I
trust the compiler to be allowed to optimize? What can I do to help
the compiler optimize?


Two rules are at play here, I believe. (1) The tighter the scope the
easier it is to optimize and maintain, and (2) Premature optimization is
the root of all evil.

V
Jan 13 '06 #8

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

Similar topics

4
6652
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
2092
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
2792
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?
0
12066
by: bazzer | last post by:
hey, im trying to access a microsoft access database from an ASP.NET web application in visual basic 2003.NET. i get the following error when i try running it: Server Error in '/CinemaBookingSystem' Application. -------------------------------------------------------------------------------- ERROR General error Unable to open registry key 'Temporary (volatile) Jet DSN for process
4
2570
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
3140
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...
1
3635
by: paul.hester | last post by:
Hi all, All of the classes in my DAL are static, with constants defining the stored procedures and parameters. I've been having some problems with my site which makes me wonder if there's a thread safety issue. Are consts thread safe? Would the following example create any thread safety issues? Would you recommend using static readonly members instead of constants?
13
3602
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
4145
by: Graham Wideman | last post by:
Folks: Can anyone tell me what controls php's "thread safety" feature? I have an installation where phpinfo() is showing Thread safety: enabled, whereas I need it disabled in order to work with xdebug.so. So far as I can tell, the options I used to configure php did not ask for thread-safety, and I also don't see any options to *dis*able thread-safety. Configure --help does show several threading-related options, but none for
0
9255
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
10014
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
9844
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9819
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
6514
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
5119
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...
1
3780
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
3326
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2647
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.