只是想看看这是否是正确的做事方式:
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 :(得分: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
}
答案 1 :(得分: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
}
}