我想异步启动6个线程,暂停它们并同步恢复...
它应该像这样工作:
我尝试了6个简单的布尔标志并等到它们都是true
,但那有点脏...
任何想法?
编辑(更好的可视化):
Thr1 | Initiliazing |waiting |waiting | Resuming
Thr2 | waiting |Initiliazing |waiting | Resuming
Thr3 | waiting |waiting |Initiliazing | Resuming
...
谢谢和问候, 通量
答案 0 :(得分:3)
您需要某种同步 - 根据您的线程函数,每个线程可能会发出ManualResetEvent。
编辑:感谢您的更新 - 这是一个基本的例子:
// initComplete is set by each worker thread to tell StartThreads to continue
// with the next thread
//
// allComplete is set by StartThreads to tell the workers that they have all
// initialized and that they may all resume
void StartThreads()
{
var initComplete = new AutoResetEvent( false );
var allComplete = new ManualResetEvent( false );
var t1 = new Thread( () => ThreadProc( initComplete, allComplete ) );
t1.Start();
initComplete.WaitOne();
var t2 = new Thread( () => ThreadProc( initComplete, allComplete ) );
t2.Start();
initComplete.WaitOne();
// ...
var t6 = new Thread( () => ThreadProc( initComplete, allComplete ) );
t6.Start();
initComplete.WaitOne();
// allow all threads to continue
allComplete.Set();
}
void ThreadProc( AutoResetEvent initComplete, WaitHandle allComplete )
{
// do init
initComplete.Set(); // signal init is complete on this thread
allComplete.WaitOne(); // wait for signal that all threads are ready
// resume all
}
请注意,StartThreads
方法会在线程初始化时阻塞 - 这可能是也可能不是问题。