博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用CAS实现单例模式
阅读量:4091 次
发布时间:2019-05-25

本文共 1504 字,大约阅读时间需要 5 分钟。

#include 
#include
#include
#include
long CAS(volatile unsigned long **addr, long old, long *new){
/* https://www.felixcloutier.com/x86/cmpxchg: (* Accumulator = AL, AX, EAX, or RAX depending on whether a byte, word, doubleword, or quadword comparison is being performed *) TEMP ← DEST IF accumulator = TEMP (比较) THEN ZF ← 1; DEST ← SRC; ELSE ZF ← 0; accumulator ← TEMP; DEST ← TEMP; FI; Compares the value in the AL, AX, EAX, or RAX register with the first operand (destination operand). If the two values are equal, the second operand (source operand) is loaded into the destination operand. Otherwise, the destination operand is loaded into the AL, AX, EAX or RAX register. RAX register is available only in 64-bit mode. */ long ret = 0; __asm__ volatile (" lock; cmpxchg %4, %2" : "=a" (ret), "=m" (*addr) : "m" (*addr), "0" (old), "r" (new) : "cc" ); return ret == old;}static void *single = 0x0;void* getInstance(void * arg){
if (single != NULL) {
return single; } long *p = calloc(1, sizeof(long)); *p = 8888; do{
if (single != NULL) break; if (CAS((volatile unsigned long **)&single, 0x0, p)) break; }while(1); return single;}

转载地址:http://lecii.baihongyu.com/

你可能感兴趣的文章
Leetcode 834. 树中距离之和 C++
查看>>
【机器学习】机器学习系统SysML 阅读表
查看>>
最小费用最大流 修改的dijkstra + Ford-Fulksonff算法
查看>>
最小费用流 Bellman-Ford与Dijkstra 模板
查看>>
实现高性能纠删码引擎 | 纠删码技术详解(下)
查看>>
scala(1)----windows环境下安装scala以及idea开发环境下配置scala
查看>>
zookeeper(3)---zookeeper API的简单使用(增删改查操作)
查看>>
zookeeper(4)---监听器Watcher
查看>>
zookeeper(2)---shell操作
查看>>
mapReduce(3)---入门示例WordCount
查看>>
hbase(3)---shell操作
查看>>
hbase(1)---概述
查看>>
hbase(5)---API示例
查看>>
SSM-CRUD(1)---环境搭建
查看>>
SSM-CRUD(2)---查询
查看>>
SSM-CRUD (3)---查询功能改造
查看>>
Nginx(2)---安装与启动
查看>>
springBoot(5)---整合servlet、Filter、Listener
查看>>
C++ 模板类型参数
查看>>
C++ 非类型模版参数
查看>>