2011-10-22 65 views
0

我希望异步启动6个线程,暂停他们并同步恢复...C#异步的ThreadStart和恢复同步

它应该工作像这样的:

  1. 线程1开始(thr1.start( ))
  2. 线程1取得了一些进展(获取MAC-不会忽略从TXT文件,初始化COM对象)
  3. 线程1暂停(暂停,直到所有的线程也做了同样的线程1)
  4. 线程2开始
  5. 线程2取得了一些进展
  6. 线程2暂停
  7. 线程3起
  8. 线程3取得了一些进展
  9. 线程3暂停
  10. ...
  11. 毕竟6线程暂停,他们应该恢复所有..

我试着用6个简单的布尔标志并且等到它们都是true但这相当有点脏......

有什么想法吗?

EDIT(更好的可视化):

Thr1 | Initiliazing |waiting  |waiting  | Resuming 
Thr2 | waiting  |Initiliazing |waiting  | Resuming 
Thr3 | waiting  |waiting  |Initiliazing | Resuming 
...   

感谢和格尔茨, 通量

+0

什么是你的问题域 - 可能有一些diffenrt方式来解决它 – swapneel

+0

为什么不只是执行你的主线程中的所有6'进度',然后产生额外的线程? –

+0

,因为'一些进度'需要在每个线程..有一些messageqeue问题,如果我初始化我主要的 – MariusK

回答

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方法将发生阻塞而线程初始化 - 这可能会或可能不会是一个问题。

+0

你能给我一个小例子吗?我不知道如何通过这个活动来实现它:(问候 – MariusK

+0

你能编辑你的问题,并且对你的线程做些什么 - 然后我可以给出更具体的答案。 –

+0

哇谢谢...看起来像什么即时通讯寻找!我会尝试并给予反馈!感谢您的帮助! – MariusK