2012-03-15 11 views
0

ただ、これは物事の正しい方法であるかどうかを確認したかった。スレッドCond。これは正しい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

+0

ブロッキングキューを使用して、他のスレッドが 'enqueue()'するのを待っている 'dequeue()'をブロックすることができます。 –

答えて

0

別のコンストラクトを使用すると目標を達成できます。 ManualResetEventまたはAutoResetEvent。以下は、両方のための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 
      } 
     } 
関連する問題