c/c++原子锁应用(跨平台)
前言:今天在修改amf庫時發現兩個函數,InterlockedIncrement()、InterlockedDecrement(),查資料知道這是關于原子鎖的,而這是windows下的系統函數,那么對應的linux下也應該有此函數了......
一.windows下的原子鎖
。。。。(待續)
二.linux下的原子鎖進化
2.1網上先是找到了atomic_t ,atomic_inc()這些函數,而且需要頭文件<atomic.h>頭文件,其實這個是不好用的:
最早atomic是linux內核的系統文件,我們要用就得引入內核的頭文件,帶來的也是一系列其他文件的引入,沒成功;
之后gnu把atomic_t這套引入自己的庫了,使用的時候只要引入頭文件即可,這個也不好用了,因為新的gnu已經把這套東西刪除了,即沒有atomic.h這個頭文件了;
最后,gnu加上了__sync_add_and_fetch()這一系列的函數,完美替代了之前的函數,這才是我們需要的東西。而這套東西包含在stdlib.h中,非常方便。
2.2linux最新的原子鎖
gcc從4.1.2提供了__sync_*系列的built-in函數,用于提供加減和邏輯運算的原子操作。
可以對1,2,4或8字節長度的數值類型或指針進行原子操作,其聲明如下
1.type __sync_fetch_and_add (type *ptr, type value, ...)??
2.type __sync_fetch_and_sub (type *ptr, type value, ...)??
3.type __sync_fetch_and_or (type *ptr, type value, ...)??
4.type __sync_fetch_and_and (type *ptr, type value, ...)??
5.type __sync_fetch_and_xor (type *ptr, type value, ...)??
6.type __sync_fetch_and_nand (type *ptr, type value, ...)??
7.????????? { tmp = *ptr; *ptr op= value; return tmp; }??
8.????????? { tmp = *ptr; *ptr = ~tmp & value; return tmp; }?? // nand??
9.?
10.type __sync_add_and_fetch (type *ptr, type value, ...)??
11.type __sync_sub_and_fetch (type *ptr, type value, ...)??
12.type __sync_or_and_fetch (type *ptr, type value, ...)??
13.type __sync_and_and_fetch (type *ptr, type value, ...)??
14.type __sync_xor_and_fetch (type *ptr, type value, ...)??
15.type __sync_nand_and_fetch (type *ptr, type value, ...)??
16.????????? { *ptr op= value; return *ptr; }??
17.????????? { *ptr = ~*ptr & value; return *ptr; }?? // nand?
這兩組函數的區別在于第一組返回更新前的值,第二組返回更新后的值,下面的示例引自這里 http://www.linuxidc.com/Linux/2011-06/37403.htm。
1.#include <stdio.h>??
2.#include <pthread.h>??
3.#include <stdlib.h>??
4.?
5.static int count = 0;??
6.?
7.void *test_func(void *arg)??
8.{??
9.??????? int i=0;??
10.??????? for(i=0;i<20000;++i){??
11.??????????????? __sync_fetch_and_add(&count,1);??
12.??????? }??
13.??????? return NULL;??
14.}??
15.?
16.int main(int argc, const char *argv[])??
17.{??
18.??????? pthread_t id[20];??
19.??????? int i = 0;??
20.?
21.??????? for(i=0;i<20;++i){??
22.??????????????? pthread_create(&id[i],NULL,test_func,NULL);??
23.??????? }??
24.?
25.??????? for(i=0;i<20;++i){??
26.??????????????? pthread_join(id[i],NULL);??
27.??????? }??
28.?
29.??????? printf("%d\n",count);??
30.??????? return 0;??
31.}?
對于使用atomic.h的老代碼,可以通過宏定義的方式,移植到高內核版本的linux系統上,例如
1.#define atomic_inc(x) __sync_add_and_fetch((x),1)??
2.#define atomic_dec(x) __sync_sub_and_fetch((x),1)??
3.#define atomic_add(x,y) __sync_add_and_fetch((x),(y))??
4.#define atomic_sub(x,y) __sync_sub_and_fetch((x),(y))?
總結
以上是生活随笔為你收集整理的c/c++原子锁应用(跨平台)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Dell 7559 安装Ubuntu以及
- 下一篇: 教育的未来,会是什么样子?