2012-03-15 47 views
0

只是想看看這是做事的正確方法:螺紋條件。這是正確的C++方式嗎?

Thread A { 
    pthread_lock_mutex(&mutex); 
    while(flag_set()) 
     pthread_cond_wait(&cond, &mutex); 
    read_file(); 
    pthread_unlock_mutex(&mutex); 
} 

Thread B{ 
    pthread_cond_signal(&cond); 
} 

對不起,我是很新的線程。

+0

這是C/C++ ???我不明白'自己鎖定'是什麼意思。您可以在線程繁忙時詳細說明期望的行爲嗎?我假設*我只想要第一個線程執行這個耗時的任務時,當用戶輸入*,你正在使用一個事件處理程序,然後將啓動一個異步任務?我相信簡短的答案是'不' - 但你可以告訴一個線程睡覺(.net)。 – IAbstract 2012-03-15 23:03:14

+0

你可以使用一個阻塞隊列並執行一個阻塞'dequeue()'等待某個其他線程'enqueue()' – 2012-03-15 23:08:58

回答

0

您可以通過使用另一個構造來實現您的目標 - 例如, ManualResetEventAutoResetEvent。下面是兩個C#示例:

var resetEvent = new ManualResetEvent(false); 

new Timer(o => resetEvent.Set(), null, 1, 500); // Set() is called in another thread 
               // it unblocks main thread 

resetEvent.Reset(); // main thread will be blocked in WaitOne() method 

while (true) 
{ 
    resetEvent.WaitOne(); // this waits until event is set 
    resetEvent.Reset(); // immediatelly reset it back 
    // do something 

} 

.....

var resetEvent = new AutoResetEvent(false); 

new Timer(o => resetEvent.Set(), null, 1, 500); // this is called in another thread 

resetEvent.Reset(); 

while (true) 
{ 
    resetEvent.WaitOne(); 
    // do something 

} 
0

使用Monitor.WAit和Monitor.Pulse

static readonly object _locker = new object(); 

    static void Main() 
    { 
     new thread (work1).start(); 

     new thread (work2).start(); 

    } 

    Static void work1() 
    { 
     console.writeline("work1 started"); 
     lock(_locker) 
      Monitor.Wait(_locker); //here we block the first thread until its signaled from the second thread 

     console.writeline("work1 wake up"); 
    } 

    static void work2() 
    { 
      console.writeline("work2 will a wake work1"); 
      console.readline(); 
      lock(_locker) 
      { 
       Monitor.pulse(_locker); //tell the first thread to continue working 
      } 
     }