观看Herb Sutter在C及以后的关于原子的讨论我瞥见了他的一个易于使用的锁定/解锁机制的想法,该机制可能会或可能不会出现在该语言的未来标准中.
该机制看起来像:
atomic{ // code here }
我不想等待未来的标准我自己试图实现这个,我想出的是:
#define CONCAT_IMPL(A,B) A ## B #define CONCAT(A,B) CONCAT_IMPL(A,B) # define atomic(a) { \ static_assert(std::is_same<decltype(a),std::mutex>::value,"Argument must be of type std::mutex !");\ struct CONCAT(atomic_impl_,__LINE__)\ {\ std::function<void()> func;\ std::mutex* impl;\ CONCAT(atomic_impl_,__LINE__)(std::mutex& b)\ { \ impl = &b;\ impl->lock();\ }\ CONCAT(~atomic_impl_,__LINE__)()\ { \ func();\ impl->unlock(); \ }\ } CONCAT(atomic_impl_var_,__LINE__)(a);\ CONCAT(atomic_impl_var_,__LINE__).func = [&]()
和用法:
std::mutex mut; atomic(mut){ // code here };}
问题显然是};我想删除.
这有可能吗?
解决方法
您可以使用在if语句中定义变量的技巧来完成此操作.
template <typename M> struct atomic_guard_ { explicit atomic_guard_(M& m) : lock(m) {} atomic_guard_(M const&) =delete; // Since we unfortunately have to use uniform atomic_guard_(M&&) =delete; // initialization,make it at least a little safe operator bool() const { return false; } std::lock_guard<M> lock; }; #define atomic(m) \ if (atomic_guard_<std::decay<decltype(m)>::type> _{m}) {} else int main() { std::mutex m; atomic(m) { std::cout << "a\n"; } atomic(m) // this works too,but I think this is ok std::cout << "b\n"; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。