用C++11实现spinlock
来源:互联网 发布:ocr文字识别软件mac版 编辑:程序博客网 时间:2024/04/30 03:40
我的 spin lock 代码:
#include <atomic>#include <unistd.h>struct SpinLock;struct SpinLock_t {private: std::atomic<char> stat; static const char UNLOCK_STAT = 0; static const char LOCK_STAT = 1;public: SpinLock_t() : stat(UNLOCK_STAT) {}private: friend class SpinLock; SpinLock_t(const SpinLock_t& s); SpinLock_t operator=(const SpinLock_t& s); };struct SpinLock {private: SpinLock_t *s_;public: SpinLock(SpinLock_t* s):s_(s) { char unlock_stat = SpinLock_t::UNLOCK_STAT; while (!(s_->stat).compare_exchange_weak(unlock_stat, SpinLock_t::LOCK_STAT, std::memory_order_acq_rel)) { unlock_stat = SpinLock_t::UNLOCK_STAT; sleep(0); } } ~SpinLock() { (s_->stat).store(SpinLock_t::UNLOCK_STAT, std::memory_order_release); }private: SpinLock(const SpinLock& s); SpinLock& operator=(const SpinLock& s); };
测试框架:
#include <vector>#include <iostream>#include <thread>#include "SpinLock.h"#include <mutex>using namespace std;SpinLock_t s;std::mutex m;int g = 0;void f1() { for (int i = 0; i < 10000000; ++i) { m.lock(); ++g; m.unlock(); }}void f2() { for (int i = 0; i < 10000000; ++i) { { SpinLock spinlock(&s); ++g; } }}int main(){ std::vector<std::thread> v; for (int n = 0; n < 1; ++n) { v.emplace_back(f1); v.emplace_back(f2); } for (auto& t : v) { t.join(); } cout << g << endl;}
测试结果:
在并发严重的情况下,我实现的spinlock和mutex比,运行时间略长,总体性能略差。但是我实现的spinlock开销的系统时间比mutex少了不少,spinlock本来就不是用于竞争非常严重、临界区非常长的的场景:)
0 0
- 用C++11实现spinlock
- rwsem-spinlock.c
- c#spinLock使用
- boost::atomic 实现 spinlock
- SpinLock 锁实现
- 使用yeild实现spinlock
- C# SpinLock实现
- spinlock的设计和实现
- spinlock的设计和实现
- Spinlock 的设计与实现
- spinlock的设计和实现
- JOS中 "spinlock" 的实现
- spinlock
- spinlock
- Spinlock
- spinlock
- spinlock
- spinlock
- 我们的爱情快乐
- 打开第三方Activity前判断Intent能否被解析
- 开启战斗模式
- codeforces 388C Fox and Card Game
- 产品经理知识梳理(1)-产品构思基本原则
- 用C++11实现spinlock
- java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory的解决
- openvas 6版本,迁移到colinux版本
- hdu 1116 欧拉路
- 2014年值得关注的10个开源项目(上)
- Windows 关闭端口8080 的方法(8080端口被占用)
- 编程之中使用的英文
- JAVA TIMER用法学习
- 第8章 Android数据存储与IO