I have the following code:
var x = new Thread(new ThreadStart(Delegate));
x.Start();
This will create a new thread and start it.
How can I detect that thread X has started to execute without a do while loop right after?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use a semaphore a mutex, or an Auto/ManualResetEvent.
Code
Deep explanation
One of the principles behind multithreading is non-determinism. If you don’t use proper techniques, as described above, you cannot predict the behaviour of operations done in multiple threads If you have a method like this
Then you are sure that B is never executed before A or after C. The same doesn’t apply to multithreading.
You are sure that the thread running B is
startedafter the thread running A, but in multithreading this means something different. As of MSDN and every programming book, starting a thread merely means requesting the OS to allocate proper facilities in kernel to support multithreading. If this is done (the thread is correctly created and scheduled for execution) then the method returns without error. It can happen that the OS runs the three threads in any order, depending on several factors.So if you debug them to console (think each does a
Console.WriteLine("Hello, I'm thread A/B/C"), you can get any order in different executions:A,B,C;A,C,B;B,C,Aand so on.So you now want to make sure, but really, really sure, that a particular or every thread has really started before running D. In fact, in many of the single-core CPU cases, the OS is supposed to run
Dmethod before every thread. That’s unpredictable too! So after being unable to predict when A, B and C run, you cannot predict when D runs!!Explicit synchronization is the technique to forcefully pause the execution of code and wait for an event to occur. The event depicted by the release of the semaphore depends on the context, so in your case, you’re just telling the main thread “Wait for Delegate to have started, then do whatever you want” 🙂
Alternate, inefficient method
Using semaphores is just an efficient way of doing the following with an infinite loop
Using semaphore doesn’t simply waste CPU for continuously checking if a certain flag is low or high