考虑如下代码:
#include <iostream> #include <cstdlib> #include <atomic> #include <thread> #include <mutex> class spinlock_mutex { std::atomic_flag flag = ATOMIC_FLAG_INIT; public: bool try_lock() { for (int i = 0; i<2000; ++i) { if (flag.test_and_set(std::memory_order_acquire)) continue; else { return true; } } return false; } void unlock() { flag.clear(std::memory_order_release); } }; spinlock_mutex g_mtx; int total = 0; int failed_bar = 0; int failed_foo = 0; void foo() { for (int i = 0; i<1000; ++i) { std::unique_lock<spinlock_mutex> lck(g_mtx, std::try_to_lock); if (lck.owns_lock()) { total++; std::this_thread::sleep_for(std::chrono::milliseconds(2)); } else{ --i; //then ++i. means redo once ++failed_foo; } } } void bar() { for (int i = 0; i<1000; ++i) { std::unique_lock<spinlock_mutex> lck(g_mtx, std::try_to_lock); if (lck.owns_lock()) { total--; } else { --i; //then ++i. means redo once ++failed_bar; } } } int main() { std::thread trd(foo); bar(); trd.join(); std::cout << "result=" << total; }
首先演示了如何把自定义的互斥量spinlock_mutex,放到unique_lock等RAII对象管理。
然后演示了spinlock遇到线程上下文切换,foo函数里,sleep模拟了上下文切换。对于bar线程来说,这是灾难性的,因为直到foo执行完sleep之后,才有可能释放锁。
这意味着,bar要不停的test_and_set。failed_bar计数器能清晰的指出,try_lock失败的次数。
这个例子清晰的展示了spinlock的应用场景:就是赌foo线程和bar线程在获得锁的保护区内,极少极少发生线程切换事件。如果赌对了,就能充分利用spinlock的威力。赌败了,就完蛋。
互斥量mutex是否也采取spinlock的优化技术?windows下听说过,先自旋一会儿(尝试碰运气),否则失败后才申请内核对象(互斥量)。这意味着,选择mutex的性能不一定比spinlock差。
原文链接: https://www.cnblogs.com/thomas76/p/8623596.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;
也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/397536
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!