2012-03-15 48 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 
      } 
     }