我有以下代码:
var x = new Thread(new ThreadStart(Delegate));
x.Start();这将创建一个新线程并启动它。
在没有do while循环的情况下,我如何检测线程X已经开始执行?
发布于 2012-09-13 03:05:08
使用信号量、互斥量或Auto/ManualResetEvent。
代码
//Initialize semaphore, set it to BLOCK
ManualResetEvent sema = new ManualResetEvent(false);
void Main()
{
var x = new Thread(Delegate);
//Request the system to start the thread.
//This doesn't mean the CPU will immediately run Delegate method
//but eventually it will do
x.Start(sema);
//Stop here and don't do anything on this thread until the semaphore is FREE
sema.WaitOne();
[continued main thread]
}
void Delegate(Semaphore sema){
//Unblock the semaphore
sema.Set(1);
[your code here]
}深层解释
多线程背后的原则之一是non-determinism.如上所述,如果您没有使用适当的技术,那么如果您有这样的方法,您就不能预测在多线程中完成的操作的行为
void Main()
{
A();
B();
C();
}那么你就可以确定B永远不会在A之前或C之后执行。同样的情况也不适用于多线程。
void Main()
{
new Thread(A).Start();
new Thread(B).Start();
new Thread(C).Start();
D();
}您确信运行B的线程在运行A的线程之后是started,但在多线程中这意味着不同的东西。在MSDN和每本编程书籍中,启动线程仅仅意味着请求操作系统在内核中分配适当的工具来支持多线程。如果完成了此操作(线程已正确创建并安排执行),则该方法返回时不会出现错误。操作系统可能会以任意顺序运行这三个线程,这取决于几个因素。
因此,如果您将它们调试到控制台(假设每个都执行一个Console.WriteLine("Hello, I'm thread A/B/C"),您可以在不同的执行中获得任何顺序:A,B,C;A,C,B;B,C,A等等)。
所以你现在想要确保,但真的,每个线程在运行D之前都已经启动了。事实上,在许多单核处理器的情况下,操作系统应该在每个线程之前运行D方法。这也是不可预测的!因此,在无法预测A、B和C何时运行之后,您也无法预测D何时运行!!
显式synchronization是一种强制暂停代码执行并等待事件发生的技术。信号量的释放所描述的事件依赖于上下文,所以在您的例子中,您只需要告诉主线程“等待Delegate启动,然后执行您想做的任何事情”:)
替代的、低效的方法
使用信号量只是通过无限循环执行以下操作的一种有效方法
volatile bool threadStarted = false;
void Main()
{
var x = new Thread(Delegate);
x.Start();
while (!threadStarted);
[continued main thread]
}
void Delegate(Semaphore sema){
threadStarted = true;
[your code here]
}使用信号量并不是简单地浪费CPU来持续检查某个标志是低还是高
发布于 2012-09-13 03:05:28
在最基本的级别上,您可以尝试:
if (((Thread)x).ThreadState==ThreadState.Running){
// do something interesting
}发布于 2012-09-13 03:05:37
x.ThreadState == System.Threading.ThreadState.Runninghttps://stackoverflow.com/questions/12394597
复制相似问题