- 论坛徽章:
- 44
|
spinlock这种东西用原子操作实现要不了几行,具体的代码长这样:
- class spinlock
- {
- private:
- typedef enum { Locked, Unlocked } LockState;
- std::atomic<LockState> state_;
- public:
- /// Constructor
- spinlock() noexcept : state_(Unlocked) {}
- /// Blocks until a lock can be obtained for the current execution agent.
- void lock() noexcept
- {
- while (state_.exchange(Locked, std::memory_order_acquire) == Locked) {
- /* busy-wait */
- }
- }
- /// Releases the lock held by the execution agent.
- void unlock() noexcept { state_.store(Unlocked, std::memory_order_release); }
- };
复制代码 唯一的问题就是它其实没什么大用,OS kernel用这东西可以理解,毕竟从OS kernel的角度看CPU并没有“空闲”的时候,但在用户态代码里用这东西绝大多数场合下只能烧CPU玩,你说一个用户进程霸占着CPU不还给OS到底要闹哪样。 |
|