Multithreading and static methods and static variables

I have a console application, which creates a couple of threads.
The threads start method - ThreadProc is static within the same class clalled Controller.

Within  the thread start method I have logging information and the main processing, which involes invoking another static method from another class called DBHelper

I have a question are the static methods thread safe, is there a possibility that they could be exceute only once. WHat about static variables.
In the code snippet below will the DBProcedure static method from the DBHelper class be executed twice at all times, assuming there are two threads created. I perform some database processing in the DBprocedure method.

Currenlty I do not have any locking inside the DBprocedure method.


using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Text;
using System.Threading;
using System.Configuration;
 
 
 
 
 
namespace EC
{
class Controller
{
 
// Create and open an output log file 
 
static FileStream fs = new FileStream(Constants.LogFile, FileMode.Append, FileAccess.Write); 
 
static StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
enum StateThread { Nothing, Running, Finished, Joined };
static Dictionary<Thread, StateThread> threadTracker = new Dictionary<Thread, StateThread>();
 
static string strConnection = ConfigurationManager.AppSettings["DBConnection"];
 
static string strMinTimeStamp = Constants.Empty;
 
[STAThread]
 
static void Main (string[] args) 
{
Thread threadMain = new Thread(new ThreadStart(ThreadProc));
threadMain.Name = Constants.MAIN;
threadTracker.Add(threadMain, StateThread.Running);
 
Thread threadSecondary = null;
 
//Check if the Destination Table parameter is passed and is not the Default value
 
if ((args.Length > 2) && ((args[2].ToString()) != Constants.MAIN))
 
{
threadSecondary = new Thread(new ThreadStart(ThreadProc));
threadSecondary.Name = args[2];
threadTracker.Add(threadSecondary, StateThread.Running);
strDestination = threadSecondary.Name;
}
 
 
strGetTimestamp = String.Format(Constants.TimeStampSQL, args[0], args[0]+ Constants.TimeGap);
minTimeStamp = DBHelper.DBReader(strGetTimestamp, strConnection);
strMinTimeStamp = DBHelper.ToHexString(minTimeStamp);
 
 
 
 
// Start the Threads
lock (threadTracker)
{
foreach (KeyValuePair<Thread, StateThread> pair in threadTracker)
{
 
pair.Key.Start();
 
}
 
}
 
// Don't exit until all threads complete
 
try
{
threadMain.Join();
if ((args.Length > 2) && ((args[2].ToString()) != Constants.MAIN))
threadSecondary.Join();
}
catch (Exception ex)
{
Console.WriteLine("Error :" + ex.Message);
sw.WriteLine(ex.StackTrace);
}
finally
{
// flush the file and close it
sw.Flush();
sw.Close();
fs.Close();
}
}
 
private static void ThreadProc()
{
lock (sw)
{ 
sw.WriteLine("Thread {0} started at {1}", Thread.CurrentThread.Name, DateTime.Now.ToLocalTime());
}
 
// Do database stuff, ******************Question*****************
DBHelper.DBProcedure(fieldA, fieldB, fieldC,Thread.CurrentThread.Name);
lock (sw)
{ 
sw.WriteLine("Thread {0} finished at {1}", Thread.CurrentThread.Name, DateTime.Now.ToLocalTime());
}
 
lock (threadTracker)
 
{
 
threadTracker.Remove(Thread.CurrentThread);
 
threadTracker.Add(Thread.CurrentThread, StateThread.Finished);
 
}
 
 
 
 
 
}
 
}
 
}

Open in new window

LVL 1
countrymeisterAsked:
Who is Participating?
 
navalarya1982Connect With a Mentor Commented:
I read that link thanks for sending that. So as per the definition method is thread safe if
"one thread will interfere and modify data elements of another thread ".. so this law is not satisfied by static methods...

if you have a global object then both the thread may change the object .. which makes them not thread safe.. so to make static method thread safe we need to add synchronization code as it is mentioned in article given by you.
0
 
SteveH_UKCommented:
Neither static methods nor static variables are inherently thread safe.  You need to code for the possibilities.

There are two possible thread execution errors:

1)  Actual concurrent access
2)  Interleaved concurrent access

The first of these is fairly rare and requires at least two processor threads.  It happens when the two .NET threads are both executing on different processor threads.

The second is more common and happens when a second thread enters the method while the first one is already in it.  In this case, they are not both executing at the same time, but they are both in the same method and this will cause just as many problems but does not require two processor threads.

Because of the way that threads are run, you cannot guarantee that both threads will be in the static method at the same time.  One might actually complete before the other starts, but you can be clear about whether you have allowed for the possibility.

You should consider creating an object that you can use for locking and include lock statements around the DB method calls.
0
 
navalarya1982Commented:
No static constructors are not thread safe. It is possible for two threads to enter them at the same time.

The safer bet would be is to use static constructors...
They are called only once when the class if first reference. Hence it is always thread safe.

more over here..
http://www.c-sharpcorner.com/UploadFile/cupadhyay/StaticConstructors11092005061428AM/StaticConstructors.aspx
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
countrymeisterAuthor Commented:
well my question is if the static method that is used as the thread start method for both the threads will cause any problems.

If it does ,  can you provide any workaround based on the code above
0
 
navalarya1982Commented:
It is certainly not going to cause any problem, but it is certainly not going to be thread safe. You can use lock on some static object to check the access on shared variables (static/non static) across threads.
0
 
countrymeisterAuthor Commented:
navalarya1982,

Just wan to confirm that static methods are not thread safe, because I thought they are
0
 
navalarya1982Commented:
yes they are not thread safe.
0
 
countrymeisterAuthor Commented:
here are some links and code which prove otherwise
http://authors.aspalliance.com/stevesmith/articles/staticthreads.asp

0
 
navalarya1982Commented:
The links -->http://authors.aspalliance.com/stevesmith/articles/staticthreads.asp

says this...
However, as you will see when you run this sample, the static method does in fact get executed by multiple threads

which makes it non thread safe,

also the other link
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_21193973.html?sfQueryTermInfo=1+method+static+thread
says this....
However, make sure that more than one threads do NOT try to UPDATE the static array together. If you do, make sure that it is done through sync. methods [lock, monitors etc].

that again makes static method non thread safe...

Hope that makes things clear...

Let me know if that doesnt :)
0
 
countrymeisterAuthor Commented:
says this...
However, as you will see when you run this sample, the static method does in fact get executed by multiple threads

Well when a thread calls a static method, it is contained in its own thread alloc.
Of couse each thread will call the static method but it will run in its own thread alloc, if there were any static variables referenced within the static method then those are not thread safe.

So I respectfully disagree with your statement that static methods are non thread safe.
Did you run the sample program, for "n" of threads from the first link, you will see they all execute the console statement, meaning each thread has its own threadalloc
0
 
navalarya1982Commented:
hey just a query from my side.. tell me what do u understand by thread safe..  I have a impression that you have some misunderstanding.
0
 
countrymeisterAuthor Commented:
0
 
countrymeisterAuthor Commented:
well I already mentioned this before in my previous comment

''
Well when a thread calls a static method, it is contained in its own thread alloc.
Of couse each thread will call the static method but it will run in its own thread alloc, if there were any static variables referenced within the static method then those are not thread safe.
"
0
 
navalarya1982Commented:
ok.. the bottom line is satic methods are not inherently thread safe. we have to write extra code to make them thread safe..

0
 
countrymeisterAuthor Commented:
navalara1992,
I guess our meaning of thread safety has some differences, but I will award you the points for your effort to help me and impart knowledge
Thanks
0
 
navalarya1982Commented:
you are welcome :)
0
All Courses

From novice to tech pro — start learning today.