---
title: "原子操作"
author: "splayx"
date: "2012-11-24T17:42:02Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-11-24T18:13:20Z"
id: 1734546
url: "https://splayx.iteye.com/blog/1734546"
---

内核自带的原子操作可以帮助高效地我们实现引用计数等功能。

 

介于这么一个前提，一个引用对象不可能同时被引用和删除。

 

以下可以简单地实现引用计数。

 

内核中的定义：

```
typedef struct { int counter; } atomic_t;
```

在复制构造函数（A::A(const A&)），和赋值构造函数（const A& A::operator=(const A&)）中

使用void atomic\_inc(atomic\_t \*v)；

在析构函数里使用 int atomic\_dec\_and\_test(atomic\_t \*v)，

表示自减之后是否为0。

 

================================================================

 

有一个更犀利的原子操作，

int atomic\_add\_unless(atomic\_t \*v, int a, int u);

If the atomic value v is not equal to u, this function adds a to v, and returns non zero. If v is equal to u then it returns zero. This is done as an atomic operation.

 

我们可以抛开这个前提“一个引用对象不可能同时被引用和删除”，做这么一件事：

假设有一个计数器初始值为C(&gt;0)，

我们可以并发地对C进行加减操作，加减操作时，操作成功的前提是C&gt;0。

 

方法就这么简单：

加，atomic\_add\_unless(&t, 1, 0);

减，atomic\_add\_unless(&t, -1, 0);

 

#以上方法已在单cpu的机器上验证。

#多cpu可以有问题，还要细看源码说明。。