Answered by:
Question about how threads work with code

Question
-
Hi,
I was trying to find the answer but the question is not as simple. I would like to understand how following code pseudo-code works:
public static class A
{
static member X (like SqlCeConnection)
static void Method(object parameter)
{
X.SomeAction();
}
}
What if Method is called from 10 threads at the same time? I do not understand whether each thread runs the code within itself or tries to execute still the same (since its static?). Is is thread safe? And what if the class was not static, what would happen?
ThanksSunday, January 3, 2010 7:23 PM
Answers
-
The code is not thread safe in and of itself. The size of the problem would depend on what X.SomeAction() actually did.Try this example several times:
using System; using System.Collections.Generic; using System.Threading; namespace ConsoleApplication_BadThreading { class Program { static void Main(string[] args) { List<Thread> myThreads = new List<Thread>(); myThreads.Add(new Thread(new ThreadStart(A.Method))); myThreads.Add(new Thread(new ThreadStart(A.Method))); myThreads.Add(new Thread(new ThreadStart(A.Method))); myThreads.Add(new Thread(new ThreadStart(A.Method))); myThreads.Add(new Thread(new ThreadStart(A.Method))); foreach (Thread t in myThreads) { t.Start(); } foreach (Thread t in myThreads) { t.Join(); } Console.WriteLine("Ending i: " + A.i.ToString()); } } public static class A { public static Int32 i = 0; static Random rnd = new Random(); public static void Method() { Thread.Sleep(100); for (Int32 j = 0; j < 100; j++) { Int32 k = i; Thread.Sleep(rnd.Next(1, 100)); i = k + 1; Console.WriteLine(A.i.ToString()); } } } }
jon.stromer.galleyTuesday, January 5, 2010 6:13 PM -
lock Statement (C#)
How to: Synchronize a Producer and a Consumer Thread (C#)
Understanding Lock Types
Let's see if the links are posting properly for me today.
Mark the best replies as answers. "Fooling computers since 1971."Tuesday, January 5, 2010 7:06 PM
All replies
-
What if Method is called from 10 threads at the same time?
It will run asynchronusly (at the same time).
Is it safe?
Depends what is in the code....if the code is set up to lock a file for editing and another version of the method is trying to do the same thing and does not handle the error then it is not safe.
What if the class was not static?
It would be called as an object and run asynchronusly.
someone is bound to correct me on this but it sounds right to me.
CS- Proposed as answer by Manishrao Patil Tuesday, January 12, 2010 11:31 AM
Sunday, January 3, 2010 11:44 PM -
Also, it is OK to have static method for something like SQL query (if I am not sharing connection, reader)?
ThanksMonday, January 4, 2010 6:27 AM -
Hi,
Thanks for putting Interesting question :)
Before touching your question I will like to share few things about static class:
1. Once a static class is loaded into the servers memory it will remain as it is, unless and untill we unload it (possibly by shutting down the application).
2. Also static class has got peculiarity because of which its datamember(s) retain their values till the class is unloaded.
For e.g private static int _x=10; the value of _x will remain the same till the life of its class (even though you re-assign new value :) )
3. Also needless to say that datamember(s) of static classes are mutually shared
Thus from above I can conclude that the datamember(s) will not have separate set of values for different threads.
* For having separate set of values you to look out for other things like sessions, statebags etc. which can work fine with the different threads.
Now answering your question:
whether each thread runs the code within itself or tries to execute still the same (since its static?). Is is thread safe?
Answer: Tries to execute still the same (since its static)
what if the class was not static, what would happen?
Answer: Then in this case create new object of this class for everythread and then set its datamember(s) via properties. This will definetly not a good practice. or else use other alternatives which i prescribed above.
Do let us know your feedback on this and dont forget to mark it as "Answer" if it helps :)
Manish Patil http://patilmanishrao.wordpress.com Posting is provided AS IS with no warranties, and confers no rights.- Proposed as answer by Manishrao Patil Tuesday, January 12, 2010 11:31 AM
Monday, January 4, 2010 9:22 AM -
Thanks, well now there are two opposite answers:
While the first says, calling static method from 10 thrads runs it 10x times on each thread, the secod says all threads try to execute the same code (then I would not work in multithread environment?) . Anyone could help further?
PS: Why it is not a good practice to call one class (its instances) among threads? I thought its quite common.Monday, January 4, 2010 9:50 AM -
Thanks, well now there are two opposite answers:
While the first says, calling static method from 10 thrads runs it 10x times on each thread, the secod says all threads try to execute the same code (then I would not work in multithread environment?) . Anyone could help further?
PS: Why it is not a good practice to call one class (its instances) among threads? I thought its quite common.
The answers sound the same to me.....Manishrao gave some extra info on Static classes and a better explantion/answer to "what if the class was not static, what would happen?"
Here is a good thread with the same question...in that thread there is another good link: http://bytes.com/topic/c-sharp/answers/249022-using-static-methods-apotentially-multithreaded-environment
csTuesday, January 5, 2010 2:39 AM -
Hi,
Well as CountryStyle said we both are trying to explain the same thing.
To some extend static variables/datamember(s) behave as like variable marked as constant or like readonly properties. Hence it will be good if we use static variables where the value is not going to change (e.g connectionstring).Why it is not a good practice to call one class (its instances) among threads?
Answer: Well if class object / instance consumes less memory/very small/neglisible then there is no issue. But if the same is memory eater then just think how badly the server will become busy for every created instance or object of that class. I pointed out this because your e.g. was wrt database operations which quite often can be resource consuming.
Also link provided by CountryStyle is very informative.
Manish Patil http://patilmanishrao.wordpress.com Posting is provided AS IS with no warranties, and confers no rights.Tuesday, January 5, 2010 11:24 AM -
The code is not thread safe in and of itself. The size of the problem would depend on what X.SomeAction() actually did.Try this example several times:
using System; using System.Collections.Generic; using System.Threading; namespace ConsoleApplication_BadThreading { class Program { static void Main(string[] args) { List<Thread> myThreads = new List<Thread>(); myThreads.Add(new Thread(new ThreadStart(A.Method))); myThreads.Add(new Thread(new ThreadStart(A.Method))); myThreads.Add(new Thread(new ThreadStart(A.Method))); myThreads.Add(new Thread(new ThreadStart(A.Method))); myThreads.Add(new Thread(new ThreadStart(A.Method))); foreach (Thread t in myThreads) { t.Start(); } foreach (Thread t in myThreads) { t.Join(); } Console.WriteLine("Ending i: " + A.i.ToString()); } } public static class A { public static Int32 i = 0; static Random rnd = new Random(); public static void Method() { Thread.Sleep(100); for (Int32 j = 0; j < 100; j++) { Int32 k = i; Thread.Sleep(rnd.Next(1, 100)); i = k + 1; Console.WriteLine(A.i.ToString()); } } } }
jon.stromer.galleyTuesday, January 5, 2010 6:13 PM -
lock Statement (C#)
How to: Synchronize a Producer and a Consumer Thread (C#)
Understanding Lock Types
Let's see if the links are posting properly for me today.
Mark the best replies as answers. "Fooling computers since 1971."Tuesday, January 5, 2010 7:06 PM