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

Home Posts Topics Members FAQ

Static Functions in a Multi Threaded App

Is it safe to create a static function in a multi threaded application
? As an example, I have a function that logs errors ,exceptions and
some informational data
public static void Log(....)
{
//
}

There are multiple threads in this application that call this function.
Is there any advantage if each thread creates an instance of the
class(I would remove the static) and uses it ? The function itself does
not access any instance variables. Will there be any thread saefty
issues if it is static. ?

Thank You

SRLoka

Nov 17 '05 #1
9 2899
SRLoka,

It all depends on what you are doing in the function. Just because you
arent accessing fields (static or instance), doesn't mean that you won't run
into threading issues.

Your best bet would be to place the MethodImpl attribute on the method,
passing the MethodImplOptio ns.Synchronized value into the constructor. This
will ensure that access to the Log method is synchronized.

If you created a separate class instance on each thread, it wouldn't
necessarily work, since they might all access the same file, and you could
end up interweaving the writes to the file in between each other (if you did
multiple writes per call to Log).

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Seenu" <Sr************ *****@gmail.com > wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
Is it safe to create a static function in a multi threaded application
? As an example, I have a function that logs errors ,exceptions and
some informational data
public static void Log(....)
{
//
}

There are multiple threads in this application that call this function.
Is there any advantage if each thread creates an instance of the
class(I would remove the static) and uses it ? The function itself does
not access any instance variables. Will there be any thread saefty
issues if it is static. ?

Thank You

SRLoka

Nov 17 '05 #2
I am trying to visualize how a static function would be executed at
runtime. I can understand the problem if I use an instance and they all
access the same file. But in my case, I am logging to a database. How
would that still create threading issues ? BTW, this app runs on a
multi cpu machine.

Thanks

Nov 17 '05 #3
Seenu,

Well, depending on how you are allocating the connection (do you have
one connection that you hold on a static level, or are you creating one each
time the function is iterated). Also, do you execute more than one command
in the method? These are the things you have to worry about.

Basically, if you are writing to a database, you would create your
commands and then execute them. Since everything is created on the stack
(at least the references to the objects you make), and not to static fields,
you should have no problem. I would just make sure that you wrap multiple
statements in a transaction so that it is consistent.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard. caspershouse.co m

"Seenu" <Sr************ *****@gmail.com > wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
I am trying to visualize how a static function would be executed at
runtime. I can understand the problem if I use an instance and they all
access the same file. But in my case, I am logging to a database. How
would that still create threading issues ? BTW, this app runs on a
multi cpu machine.

Thanks

Nov 17 '05 #4

As long as the database connection is created/released from the pool
within Log() then it's thread safe. There would be no difference if
the method is static or instance based since all it's resources are
internalized.

For performance you might want to consider having Log() just push the
log items into a queue (which needs to be synchronized) and have a
background thread put them in the database asynchronously--depends on
how many log calls you're making.

HTH,

Sam
On 14 Jun 2005 08:50:09 -0700, "Seenu" <Sr************ *****@gmail.com >
wrote:
Is it safe to create a static function in a multi threaded application
? As an example, I have a function that logs errors ,exceptions and
some informational data
public static void Log(....)
{
//
}

There are multiple threads in this application that call this function.
Is there any advantage if each thread creates an instance of the
class(I would remove the static) and uses it ? The function itself does
not access any instance variables. Will there be any thread saefty
issues if it is static. ?

Thank You

SRLoka


Nov 17 '05 #5
For argument sake, leaving aside my requirements, say I have a
function
public static void Log(...)
{
int i=0;
Statement1;
Statement2;
i++;
....
....
StatementN
}

If on a dual cpu machine, one thread calls this function and then
another thread calls it before the procedure is completed(its possible
right ?), will variable i be a separate copy for each ? Since only one
copy of the object(function ) exists, are variables still maintained
separately for each thread ? Are variables maintained on the stack per
process or per application ?
May be this is a dumb question but I am trying to understand some
internals.

Thanks

Nov 17 '05 #6

"Seenu" <Sr************ *****@gmail.com > wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
For argument sake, leaving aside my requirements, say I have a
function
public static void Log(...)
{
int i=0;
Statement1;
Statement2;
i++;
....
....
StatementN
}

If on a dual cpu machine, one thread calls this function and then
another thread calls it before the procedure is completed(its possible
right ?), will variable i be a separate copy for each ? Since only one
copy of the object(function ) exists, are variables still maintained
separately for each thread ? Are variables maintained on the stack per
process or per application ?
May be this is a dumb question but I am trying to understand some
internals.

Thanks


Yes, i is a local variable, that means it's stack allocated and as each
thread has it's own stack, each thread gets it's own private copy of i.

Willy.
Nov 17 '05 #7
So a separate stach for each thread would mean if the static function
does not access any outside variables, it is thread safe ? Am I correct
?

Nov 17 '05 #8

"Seenu" <Sr************ *****@gmail.com > wrote in message
news:11******** *************@g 43g2000cwa.goog legroups.com...
So a separate stach for each thread would mean if the static function
does not access any outside variables, it is thread safe ? Am I correct
?

No you cannot generalize this, the method in the sample you posted, is
indead thread safe because the local variable i of type int is on the
callers stack. But if a local variable holds a reference to shared state,
it's not threadsafe.

Willy.

Nov 17 '05 #9
That is what I would do. As you don't want your source threads waiting for
log updates. Create your static log class. In 2.0 you can even use Static
on the class itself to get compile checks to allow only static members.
Anyway, add a queue (either a sync queue or my Bounded blocking queue on the
CodeProject) to the class. Now create a new worker thread in the Log class
that blocks on Dequeue on the queue. And put a Log.Message(str ng msg)
static method that adds msg to the queue. Now the reader thread will just
keep servicing the queue or block when it is empty. Now you can keep one
connection open and send updates in sync one after another.

--
William Stacey [MVP]

"Samuel R. Neff" <in**********@n ewsgroup.nospam > wrote in message
news:hb******** *************** *********@4ax.c om...

As long as the database connection is created/released from the pool
within Log() then it's thread safe. There would be no difference if
the method is static or instance based since all it's resources are
internalized.

For performance you might want to consider having Log() just push the
log items into a queue (which needs to be synchronized) and have a
background thread put them in the database asynchronously--depends on
how many log calls you're making.

HTH,

Sam
On 14 Jun 2005 08:50:09 -0700, "Seenu" <Sr************ *****@gmail.com >
wrote:
Is it safe to create a static function in a multi threaded application
? As an example, I have a function that logs errors ,exceptions and
some informational data
public static void Log(....)
{
//
}

There are multiple threads in this application that call this function.
Is there any advantage if each thread creates an instance of the
class(I would remove the static) and uses it ? The function itself does
not access any instance variables. Will there be any thread saefty
issues if it is static. ?

Thank You

SRLoka

Nov 17 '05 #10

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

Similar topics

6
4916
by: jacob navia | last post by:
As far as I understood the standard, non-automatic variables (static/global data) can't be cached in registers because in a multiprocessing or multi-threading environment, another thread/processor could read a wrong value from main memory, if the compiler would do so Even if the variable has local scope (static variable enclosed in a function scope) this would still hold since another processor/thread could run the same code at the same...
10
429
by: Peter Kirk | last post by:
Hi there I have a question about static variables. There is a function which returns a pointer to a structure "AStructure". The function has a static local variable of type AStructure, and it is the address of this variable which is returned. Is this good practice? See this pseudo code: AStructure *my_function()
2
2923
by: David | last post by:
I have a static method in the dll that looks like this public static int myStaticFunction(int input){ } My question is, should I use a mutex inside the function to ensure that the function is threadsafe? This is used for ASP.NET. I am asking this question without knowing how IIS works as a multi-threaded application. Does each websession get a thread? If so, if two users are calling the static function at the same time, do they
10
21364
by: Simon | last post by:
Hi, I have something like // // common.h const unsigned long m_dwStyle = 0x123; // // common.h
16
10833
by: Chris | last post by:
Looking at some code I see a declaration inside a function like static const string s("some string"); Does the static serve any purpose here?
5
2360
by: Sam.Gundry | last post by:
Hi, I wish to share an object through a bunch of functions without declaring it globally. I have achieved this through the following function: VideoReceiver* getReceiver() { static VideoReceiver *vr = new VideoReceiver(); return vr;
14
3460
by: subramanian100in | last post by:
In the following link, http://www.c-faq.com/malloc/retaggr.html The following ANSWER is given to a question(comp.lang.c FAQ list · Question 7.5a) : Whenever a function returns a pointer, make sure that the pointed-to memory is properly allocated. For example, make sure you have not done something like
12
1709
by: Peter K | last post by:
Say I have this class public class Simple { private string name; public string Name { get { return name; } set { name = value; }
1
2813
by: lide.wyb | last post by:
We are using only the OpenSSL cryptographic functionality, the EVP and HMAC functions, in a multi-threaded application. Do we need to do anything to ensure thread safety ? The documentation mentions CRYPTO_set_locking_callback() and CRYPTO_set_id_callback() but we are not calling these functions nor have we put critical sections in our own code before calling the cryptographic functions. We are experiencing some crashes and attempting to...
0
10620
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
10369
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
10372
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
10110
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...
0
9187
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...
0
5546
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
5682
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4329
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
3851
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.