MultiThreading - Synchronization issues
-
Hi, My scenario is as follows: I spawn mukltiple threads simultaneously and all threads invoke functions simultaneously. These functions are in a single threaded application. What happens if one thread invokes the function and before it completes its processing, another thread also invoke it? Will both the threads execute the function simultaneously or will one thread complete its operation and only then the other will start processing?. In my case I want one specific function to be executed synchronously. Only one thread should execute it at a time because it makes use of certain resources whic can be used by only one thread at a time. How to lock the entire method? Can lock(this) { //Code goes here... } be used in this scenario. It would be better if any of you are able to suggest a solution for this.
Thanks and Regards Madhu
-
Hi, My scenario is as follows: I spawn mukltiple threads simultaneously and all threads invoke functions simultaneously. These functions are in a single threaded application. What happens if one thread invokes the function and before it completes its processing, another thread also invoke it? Will both the threads execute the function simultaneously or will one thread complete its operation and only then the other will start processing?. In my case I want one specific function to be executed synchronously. Only one thread should execute it at a time because it makes use of certain resources whic can be used by only one thread at a time. How to lock the entire method? Can lock(this) { //Code goes here... } be used in this scenario. It would be better if any of you are able to suggest a solution for this.
Thanks and Regards Madhu
Hello Forget the crap I said in my last post. I told you my mind was crashed back then. Anyway, here is the right thing. Two Approaches: Note: x is your object 1- Use the lock statement:
lock(x)
{
DoSomething();
}2- Use the
System.Object obj = (System.Object)x;
System.Threading.Monitor.Enter(obj);
try
{
DoSomething();
}
finally
{
System.Threading.Monitor.Exit(obj);
}The above codes are quoted from MSDN. I think you already got that by now, but I want to post that just in case you didn't.
Regards:rose: