0、头文件引用
#include<atomic.h>
1、原子变量的定义
// 内核态
typedef struct tagSessionFwdStatistics
{
atomic_t stTotalSessNum;
atomic64_t astSessionAllStatCount[SESSION_ALLSTAT_TYPE_MAX];
}SESSION_FWD_STATISTICS_S;
// 用户态
typedef struct tagSessionFwdStatistics
{
atomic32_t stTotalSessNum;
atomic64_t astSessionAllStatCount[SESSION_ALLSTAT_TYPE_MAX];
}SESSION_FWD_STATISTICS_S;
对于32位的结构体使用会有变化。
2、读
// 内核态
0 == atomic_read(&(pstSessionMdc->stSessStat.stTotalRelationNum))
// 用户态
0 == atomic32_read(&(pstSessionMdc->stSessStat.stTotalRelationNum))
3、自增(不要相信返回值,会返回原来的值)
// 内核态
atomic_inc(&pstCfgData->astStatFailCnt[SESSION_STAT_INV6][enStatFailType]);
//用户态
atomic32_inc(&pstCfgData->astStatFailCnt[SESSION_STAT_INV6][enStatFailType]);
4、自减(不要相信返回值,会返回原来的值)
// 内核态
atomic_dec(&(pstCfg->stSessStat.stTotalSessNum));
// 用户态
atomic32_dec(&(pstCfg->stSessStat.stTotalSessNum));
5、初始化设置
// 内核态
atomic_set(&pstSession->stSessionBase.stRefCount.stCount, 1);
// 用户态
atomic32_set(&pstSession->stSessionBase.stRefCount.stCount, 1);
6、增加指定值(参数位置不同)
// 内核态
atomic_add(1, &pstStat->astSessAllStatCount[enSessAllStatType]);
// 用户态
atomic32_add(&pstStat->astSessAllStatCount[enSessAllStatType], 1);
减去指定值不再示例
7、原子数先自增,然后再返回新值
// 内核态
(UINT)atomic_inc_return(&pstCfg->stSessStat.stTotalSessNum);
//用户态
(UINT)atomic32_add_return(&pstCfg->stSessStat.stTotalSessNum, 1);
注意函数不同了
8、原子数先自减,自减后等于0返回1,不等于0返回0
// 内核态
atomic_dec_and_test(&pstSession->stSessionBase.stRefCount)
// 用户态
atomic32_dec_and_test(&pstSession->stSessionBase.stRefCount)
9、当原子数不等于0才加1,原子数等于0时返回值为0
// 内核态
0 == atomic_inc_not_zero(&pstSessionBase.stRefCount.stCount)
// 用户态
0 == atomic32_add_unless(&pstSession->stSessionBase.stRefCount.stCount, 1, 0)
10、先自减,再返回新的值(一般会来判断新值是否为0),替换后要指定减数
// 内核态
0 == atomic_dec_return(&pstIp4LogNode->stReferenceCnt)
// 用户态
0 == atomic32_sub_return(&pstIp4LogNode->stReferenceCnt, 1)