我需要一些機制讓人想起Win32重置事件,我可以通過具有相同的語義與WaitForSingleObject()和WaitForMultipleObjects()(只需要..SingleObject()版本此時此刻) 。但我的目標是多平臺,所以我擁有的是boost :: threads(AFAIK)。我想出了下面的課,想問一下潛在的問題以及是否能夠完成任務。提前致謝。Win32重置事件像同步類與升壓C++
class reset_event
{
bool flag, auto_reset;
boost::condition_variable cond_var;
boost::mutex mx_flag;
public:
reset_event(bool _auto_reset = false) : flag(false), auto_reset(_auto_reset)
{
}
void wait()
{
boost::unique_lock<boost::mutex> LOCK(mx_flag);
if (flag)
return;
cond_var.wait(LOCK);
if (auto_reset)
flag = false;
}
bool wait(const boost::posix_time::time_duration& dur)
{
boost::unique_lock<boost::mutex> LOCK(mx_flag);
bool ret = cond_var.timed_wait(LOCK, dur) || flag;
if (auto_reset && ret)
flag = false;
return ret;
}
void set()
{
boost::lock_guard<boost::mutex> LOCK(mx_flag);
flag = true;
cond_var.notify_all();
}
void reset()
{
boost::lock_guard<boost::mutex> LOCK(mx_flag);
flag = false;
}
};
示例用法;
reset_event terminate_thread;
void fn_thread()
{
while(!terminate_thread.wait(boost::posix_time::milliseconds(10)))
{
std::cout << "working..." << std::endl;
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
}
std::cout << "thread terminated" << std::endl;
}
int main()
{
boost::thread worker(fn_thread);
boost::this_thread::sleep(boost::posix_time::seconds(1));
terminate_thread.set();
worker.join();
return 0;
}
編輯
我照着邁克爾·伯爾的建議固定代碼。我的「非常簡單」測試表明沒有問題。
class reset_event
{
bool flag, auto_reset;
boost::condition_variable cond_var;
boost::mutex mx_flag;
public:
explicit reset_event(bool _auto_reset = false) : flag(false), auto_reset(_auto_reset)
{
}
void wait()
{
boost::unique_lock<boost::mutex> LOCK(mx_flag);
if (flag)
{
if (auto_reset)
flag = false;
return;
}
do
{
cond_var.wait(LOCK);
} while(!flag);
if (auto_reset)
flag = false;
}
bool wait(const boost::posix_time::time_duration& dur)
{
boost::unique_lock<boost::mutex> LOCK(mx_flag);
if (flag)
{
if (auto_reset)
flag = false;
return true;
}
bool ret = cond_var.timed_wait(LOCK, dur);
if (ret && flag)
{
if (auto_reset)
flag = false;
return true;
}
return false;
}
void set()
{
boost::lock_guard<boost::mutex> LOCK(mx_flag);
flag = true;
cond_var.notify_all();
}
void reset()
{
boost::lock_guard<boost::mutex> LOCK(mx_flag);
flag = false;
}
};
非常感謝Michael。你能解釋一下最後一項嗎? – fgungor 2011-01-14 16:33:15