您可以通過使用另一個構造來實現您的目標 - 例如, 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
}
這是C/C++ ???我不明白'自己鎖定'是什麼意思。您可以在線程繁忙時詳細說明期望的行爲嗎?我假設*我只想要第一個線程執行這個耗時的任務時,當用戶輸入*,你正在使用一個事件處理程序,然後將啓動一個異步任務?我相信簡短的答案是'不' - 但你可以告訴一個線程睡覺(.net)。 – IAbstract 2012-03-15 23:03:14
你可以使用一個阻塞隊列並執行一個阻塞'dequeue()'等待某個其他線程'enqueue()' – 2012-03-15 23:08:58