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 9 2883
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 MethodImplOptions.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.com
"Seenu" <Sr*****************@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.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
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
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.com
"Seenu" <Sr*****************@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.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
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
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
"Seenu" <Sr*****************@gmail.com> wrote in message
news:11**********************@g43g2000cwa.googlegr oups.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.
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
?
"Seenu" <Sr*****************@gmail.com> wrote in message
news:11*********************@g43g2000cwa.googlegro ups.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.
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(strng 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**********@newsgroup.nospam> wrote in message
news:hb********************************@4ax.com... 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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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...
|
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...
|
by: Simon |
last post by:
Hi,
I have something like
//
// common.h
const unsigned long m_dwStyle = 0x123;
//
// common.h
|
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?
|
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...
|
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...
|
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; }
|
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...
|
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
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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,...
|
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,...
|
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: 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...
|
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...
|
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...
|
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...
| |