atomic integer

本文介绍了一个用于多线程环境的原子整数类AtomicInteger的实现。该类提供了线程安全的整数操作,如获取当前值、前缀和后缀的增减操作等,并利用了__sync_val_compare_and_swap及__sync_fetch_and_add等原子操作函数来确保操作的原子性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*************************************************************************
    > File Name: AtomicInteger.h
    > Author: wangzhicheng
    > Mail: 2363702560@qq.com
    > Created Time: 2017-02-20
    > statement: provide atomic integer and operation for multithread
 ************************************************************************/
#ifndef _ATOMIC_INTEGER_H_
#define _ATMOIC_INTEGER_H_
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <iostream>
using namespace std;
/**
 *@brief provide atomic integer and operation for multithread
 */
template<class T>
class AtomicInteger {
	private:
		volatile T value;	// prevent g++ to optimize the value
	public:
		AtomicInteger():value(0) {
		}
		/*
 		 *@brief get the original value 
 		 * */
		T GetValue() {
			// if value == 0 then value = 0 and return the original value
			return __sync_val_compare_and_swap(&value, 0, 0);
		}
		/*
 		 *@brief suffix ++ such as a++
 		* */
		T operator ++ (int) {
			return __sync_fetch_and_add(&value, 1);
		}
		/*
 		 *@brief prefix ++ such as ++a
 		* */
		T operator ++ () {
			return __sync_add_and_fetch(&value, 1);
		}
		/*
 		 *@brief 加某个数
 		* */
		T operator + (int num) {
			return __sync_add_and_fetch(&value, num);
		}
		/*
 		 *@brief 减某个数
 		* */
		T operator - (int num) {
			return __sync_add_and_fetch(&value, -num);
		}
		/*
 		 *@brief suffix -- such as a--
 		* */
		T operator -- (int) {
			return __sync_fetch_and_add(&value, -1);
		}
		/*
 		 *@brief prefix -- such as --a
 		* */
		T operator -- () {
			return __sync_add_and_fetch(&value, -1);
		}
		/*
 		 *@brief add operation
 		* */
		T operator + (const T &other) {
			return __sync_add_and_fetch(&value, other);
		}
		/*
 		 *@brief = operation
 		* */
		T operator = (const T &newValue) {
			return __sync_lock_test_and_set(&value, newValue);
		}
		
};//ns
typedef AtomicInteger<uint64_t>AtomicInt64;
typedef AtomicInteger<uint32_t>AtomicInt32;

#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值