一、先来看一个非原子操作演示案例
i++的自增操作
- 在C/C++中,一个简单的自加操作需要涉及三个步骤:
- 第一步:将值从内存中取到寄存器中
- 第二步:在寄存器中将值增加
- 第三步:将增加后的值重新写入内存
![](https://i-blog.csdnimg.cn/blog_migrate/0af34bdffcc668a2940aa2eb177611c9.png)
测试代码
#include <stdio.h>
int i = 0;
int main()
{
i++;
return 0;
}
- 输入下面的命令对.c文件进行汇编,生成一个.s文件,.s文件中都是汇编代码
gcc -S -o test_i++.s test_i++.c
- 查看test_i++.s文件可以看到如下的关键内容(下图红圈部分)。因此一个i++对应的操作是:
- 1.把变量i从内存(RAM)加载到寄存器
- 2.把寄存器的值加1
- 3.把寄存器的值写回内存(RAM)
![](https://i-blog.csdnimg.cn/blog_migrate/a751900b8f1d31f4b32a51556039ff4d.png)
- 从上面可以看出,一个自加操作都不是原子的。例如,下图的执行情况就导致i变量的结果仅仅⾃增了⼀次,而不是两次,导致实际结果与预期结果不对
![](https://i-blog.csdnimg.cn/blog_migrate/f020abe2c67a8838a0a0e92f826f36a3.png)
多线程下的测试案例
- 下面演示一个全局变量在多个线程中进行自增操作,最终的结果会与预期的不一致(多运行几次下面的程序)
//non-atomic_i++_thread.cpp
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define THREAD_NUM 2 //线程的数量
#define FOR_LOOP_NUM 100000 //线程中for循环的次数
static int num = 0;
void *thread_fun(void *arg)
{
//多个线程同时执行num++的操作
for(int i = 0; i < FOR_LOOP_NUM; ++i)
{
num++;
}
pthread_exit(NULL);
}
int main()
{
pthread_t tid[THREAD_NUM] = {0};
//启动线程
for(int i = 0; i < THREAD_NUM; ++i)
{
if(pthread_create(&tid[i], NULL, thread_fun, NULL) != 0)
{
perror("pthread_create");
}
}
//等待所有线程结束
for(int i = 0; i < THREAD_NUM; ++i)
{
if(pthread_join(tid[i], NULL) != 0)
{
perror("pthread_join");
}
}
printf("num actual: %d, expected: %d\n", num, THREAD_NUM * FOR_LOOP_NUM);
return 0;
}
二、gcc/g++提供的原子操作
相关接口
type __sync_fetch_and_add (type *ptr, type value, ...); //+
type __sync_fetch_and_sub (type *ptr, type value, ...); //-
type __sync_fetch_and_or (type *ptr, type value, ...); // |
type __sync_fetch_and_and (type *ptr, type value, ...); // &
type __sync_fetch_and_xor (type *ptr, type value, ...); // ^
type __sync_fetch_and_nand (type *ptr, type value, ...); //与非(与门和非门叠加)
type __sync_add_and_fetch (type *ptr, type value, ...);
type __sync_sub_and_fetch (type *ptr, type value, ...);
type __sync_or_and_fetch (type *ptr, type value, ...);
type __sync_and_and_fetch (type *ptr, type value, ...);
type __sync_xor_and_fetch (type *ptr, type value, ...);
type __sync_nand_and_fetch (type *ptr, type value, ...);
// 举例说明
int i = 1;
__sync_fetch_and_add(&i, 1) //相当于i++
__snyc_add_and_fetch(&i, 1) //相当于++i
- 下面是自旋锁,自旋锁与互斥锁的区别就是, 不会让出CPU睡眠:
- 优点:效率高
- 缺点:一直占用CPU,如果一直没有获得锁,CPU效率降低
//这两个函数是典型的CAS接口,使用案例可以参阅: https://blog.csdn.net/qq_41453285/article/details/106589402
bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...);
type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...);
//将*ptr设为value并返回*ptr操作之前的值
type __sync_lock_test_and_set (type *ptr, type value, ...);
//置*ptr为0
void __sync_lock_release (type *ptr, ...);
三、将文章最开始的演示案例改为原子操作
- 有了这些原子操作,我们就可以将值的自增操作放到一个原子中去进行,这样就不会出现错误了
代码如下
- 代码没有多大改动,只是在thread_fun()函数中调用了__sync_fetch_and_add()原子接口
//atomic_i++_thread.cpp
#include <stdio.h>
#include <pthread.h>
#define THREAD_NUM 2 //线程的数量
#define FOR_LOOP_NUM 100000 //线程中for循环的次数
int num = 0;
void *thread_fun(void *arg)
{
for(int i = 0; i < FOR_LOOP_NUM; ++i)
{
__sync_fetch_and_add(&num, 1);
}
}
int main()
{
pthread_t tid[THREAD_NUM];
//启动线程
for(int i = 0; i < THREAD_NUM; ++i)
{
if(pthread_create(&tid[i], NULL, thread_fun, NULL) != 0)
{
perror("pthread_create");
}
}
//等待所有线程结束
for(int i = 0; i < THREAD_NUM; ++i)
{
if(pthread_join(tid[i], NULL) != 0)
{
perror("pthread_join");
}
}
printf("num actual: %d, expected: %d\n", num, THREAD_NUM * FOR_LOOP_NUM);
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/5799e9dab5a4c8c29360037d085f5149.png)
四、原子操作底层是如何实现的哪
以X86结构为例
- 下面以X86结构为例,Intel X86指令集提供了指令前缀lock用于锁定前端串⾏总线FSB,保证了指执行时不会收到其他处理器 的干扰。比如:
static int lxx_atomic_add(int *ptr, int increment)
{
int old_value = *ptr;
__asm__ volatile("lock; xadd %0, %1 \n\t"
: "=r"(old_value), "=m"(*ptr)
: "0"(increment), "m"(*ptr)
: "cc", "memory");
return *ptr;
}
- 使用lock指令前缀之后,处理期间对count内存的并发访问(Read/Write)被禁⽌,从⽽保证了指令的原子性。如图所示:
![](https://i-blog.csdnimg.cn/blog_migrate/53c30bfdc14e619c42596c7d1d81b7e6.png)
演示案例
- 例如下面我们将上面的程序进行修改,让其不调用__sync_fetch_and_add()接口,直接调用上面的lxx_atomic_add()函数也是相同的效果
//lxx_atomic_add_i++_thread.cpp
#include <stdio.h>
#include <pthread.h>
#define THREAD_NUM 2 //线程的数量
#define FOR_LOOP_NUM 100000 //线程中for循环的次数
int num = 0;
static int lxx_atomic_add(int *ptr, int increment)
{
int old_value = *ptr;
__asm__ volatile("lock; xadd %0, %1 \n\t"
: "=r"(old_value), "=m"(*ptr)
: "0"(increment), "m"(*ptr)
: "cc", "memory");
return *ptr;
}
void *thread_fun(void *arg)
{
for(int i = 0; i < FOR_LOOP_NUM; ++i)
{
lxx_atomic_add(&num, 1);
}
}
int main()
{
pthread_t tid[THREAD_NUM];
//启动线程
for(int i = 0; i < THREAD_NUM; ++i)
{
if(pthread_create(&tid[i], NULL, thread_fun, NULL) != 0)
{
perror("pthread_create");
}
}
//等待所有线程结束
for(int i = 0; i < THREAD_NUM; ++i)
{
if(pthread_join(tid[i], NULL) != 0)
{
perror("pthread_join");
}
}
printf("num actual: %d, expected: %d\n", num, THREAD_NUM * FOR_LOOP_NUM);
return 0;
}
![](https://i-blog.csdnimg.cn/blog_migrate/497003aa84a8d73a2919e194ede5356a.png)
![](https://i-blog.csdnimg.cn/blog_migrate/a41691dbc13f7ab4d108a27e8c6b63a3.png)
- 注意上⾯标红的⽂字:在执⾏伴随指令期间使处理器的LOCK#信号有效(将指令变为原⼦指令)。在多处理器环境中,LOCK# 信号确保处理器在信号有效时独占使⽤任何共享存储器。如果LOCK前缀与这些指令之一一起使⽤,并且源操作数是内存操作 数,则可能会⽣成未定义的操作码异常(#UD)。 如果LOCK前缀与任何不在上述列表中的指令⼀起使 ⽤,也会产⽣未定义的操作码异常。 ⽆论是否存在LOCK前缀,XCHG指令都始终声明LOCK#信号。 LOCK前缀通常与BTS指令⼀起使⽤,以在共享存储器环境中的存储器位置上执⾏读取 – 修改 – 写⼊操作
- LOCK前缀的完整性不受存储器字段对⻬的影响。 内存锁定是针对任意不对⻬的字段。 好了,到此,我们了解X86上如何⽀持原⼦操作了,我们看看内核的实现: 如⽂件:arch/x86/include/asm/atomic.h
/**
* arch_atomic_add - add integer to atomic variable
* @i: integer value to add
* @v: pointer of type atomic_t
*
* Atomically adds @i to @v.
*/
static __always_inline void arch_atomic_add(int i, atomic_t *v)
{
asm volatile(LOCK_PREFIX "addl %1,%0"
: "+m"(v->counter)
: "ir"(i)
: "memory");
}
#ifdef CONFIG_SMP
#define LOCK_PREFIX_HERE \
".pushsection .smp_locks,\"a\"\n" \
".balign 4\n" \
".long 671f - .\n" /* offset */ \
".popsection\n" \
"671:"
#define LOCK_PREFIX LOCK_PREFIX_HERE "\n\tlock; "
#else /* ! CONFIG_SMP */
#define LOCK_PREFIX_HERE ""
#define LOCK_PREFIX ""
#endif
- 也就是说在SMP的系统中,LOCK_PREFIX是lock,⽽⾮SMP系统中是空,另外CAS的代码实现也如下:
static __always_inline int atomic_cmpxchg(atomic_t *v, int old, int new)
{
return cmpxchg(&v->counter, old, new);
}
#define cmpxchg(ptr, old, new) \
__cmpxchg(ptr, old, new, sizeof(*(ptr)))
#define __cmpxchg(ptr, old, new, size) \
__raw_cmpxchg((ptr), (old), (new), (size), LOCK_PREFIX)
#define __raw_cmpxchg(ptr, old, new, size, lock) \
({ \
__typeof__(*(ptr)) __ret; \
__typeof__(*(ptr)) __old = (old); \
__typeof__(*(ptr)) __new = (new); \
switch (size) { \
case __X86_CASE_B: \
{ \
volatile u8 *__ptr = (volatile u8 *)(ptr); \
asm volatile(lock "cmpxchgb %2,%1" \
: "=a" (__ret), "+m" (*__ptr) \
: "q" (__new), "0" (__old) \
: "memory"); \
break; \
}
case __X86_CASE_W:
{
volatile u16 *__ptr = (volatile u16 *)(ptr);
asm volatile(lock "cmpxchgw %2,%1"
: "=a"(__ret), "+m"(*__ptr)
: "r"(__new), "0"(__old)
: "memory");
break;
}
case __X86_CASE_L:
{
volatile u32 *__ptr = (volatile u32 *)(ptr);
asm volatile(lock "cmpxchgl %2,%1"
: "=a"(__ret), "+m"(*__ptr)
: "r"(__new), "0"(__old)
: "memory");
break;
}
case __X86_CASE_Q:
{
volatile u64 *__ptr = (volatile u64 *)(ptr);
asm volatile(lock "cmpxchgq %2,%1"
: "=a"(__ret), "+m"(*__ptr)
: "r"(__new), "0"(__old)
: "memory");
break;
}
default:
__cmpxchg_wrong_size();
}
__ret;
})
- 对于X86的系统我们有LOCK信号去关闭CPU和内存间并发访问,做到独占访问,那么也阻⽌了其它CPU 与内存间的访问,这是⼀种低效的处理方式