大佬教程收集整理的这篇文章主要介绍了Win32重置事件,如带有boost 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; }
编辑
我根据Michael Burr的建议修改了代码.我的“非常简单”测试表明没有问题.
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; } };
>在wait()函数中,如果已设置为auto_reset,则不会重置已经发信号的事件:
void wait() { boost::unique_lock<boost::mutex> LOCK(mx_flag); if (flag) { if (auto_reset) flag = false; // <-- I think you need this return; } cond_var.wait(LOCK); if (auto_reset) flag = false; }
>在等待(const boost :: posix_time :: time_duration& dur)你应该在等待条件变量之前检查标志.>在两个等待函数中,如果等待条件变量,则可能需要重新检查该标志以确保其他某个线程在此期间未重置该事件.对于auto_reset事件尤其如此,即使多个线程正在等待事件,它也应该只释放一个服务员.
以上是大佬教程为你收集整理的Win32重置事件,如带有boost C的同步类全部内容,希望文章能够帮你解决Win32重置事件,如带有boost C的同步类所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。