本文主要是介绍base2. Atomic原子操作,Types类型转换,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
AtomicIntegerT模板类图
数据成员:
volatile T value_:一个T类型的value_
成员函数:
AtomicIntegerT():默认构造函数,令value_=0
T get():返回value_,原子性操作
T getAndAdd(T x):先获取后加x,返回value_,之后把value_+x,原子性操作
T addAndGet(T x):先加后获取x,返回value_+x,原子性操作
T incrementAndGet():自增1,先增后获取,返回value_+1
T decrementAndGet():自减1,先减后获取,返回value_-1
void add(T x):先获取后加,返回value_,之后把value_+x
void increment():自增1,先增后获取,返回value_+1
void decrement():自减1,先减后获取,返回value_-1
T getAndSet(T newValue):返回原来的value_,并将其设置为newValue
Atomic.h
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)#ifndef MUDUO_BASE_ATOMIC_H
#define MUDUO_BASE_ATOMIC_H#include <boost/noncopyable.hpp>
#include <stdint.h>namespace muduo
{namespace detail
{
template<typename T>
class AtomicIntegerT : boost::noncopyable
{public:AtomicIntegerT(): value_(0){}//noncopyable的另一种实现方式是把拷贝构造函数和赋值运算符设置成私有// uncomment if you need copying and assignment//// AtomicIntegerT(const AtomicIntegerT& that)// : value_(that.get())// {}//// AtomicIntegerT& operator=(const AtomicIntegerT& that)// {// getAndSet(that.get());// return *this;// }//返回value_,原子性操作T get(){return __sync_val_compare_and_swap(&value_, 0, 0);}//先获取后加,返回value_,之后把value_+x,原子性操作T getAndAdd(T x){return __sync_fetch_and_add(&value_, x);}//先加后获取,返回value_+x,原子性操作T addAndGet(T x){return getAndAdd(x) + x;}//自增1,先增后获取,返回value_+1T incrementAndGet(){return addAndGet(1);}//自减1,先减后获取,返回value_-1T decrementAndGet(){return addAndGet(-1);}//先获取后加,返回value_,之后把value_+xvoid add(T x){getAndAdd(x);}//自增1,先增后获取,返回value_+1void increment(){incrementAndGet();}//自减1,先减后获取,返回value_-1void decrement(){decrementAndGet();}//返回原来的value_,并将其设置为newValueT getAndSet(T newValue){return __sync_lock_test_and_set(&value_, newValue);}private://volatile的作用: 作为指令关键字,确保本条指令不会因编译器的优化而省略,且要求每次直接读值。简单地说就是防止编译器对代码进行优化//当要求使用volatile 声明的变量的值的时候,系统总是重新从它所在的内存读取数据,而不是使用保存在寄存器中的备份。即使它前面的指令刚刚从该处读取过数据。而且读取的数据立刻被保存//多线程编程时很重要volatile T value_;
};
}typedef detail::AtomicIntegerT<int32_t> AtomicInt32;
typedef detail::AtomicIntegerT<int64_t> AtomicInt64;
}#endif // MUDUO_BASE_ATOMIC_H
Types模板类
两个转换模板:
//隐式转换,将from类型转换成to类型
template<typename To, typename From>
inline To implicit_cast(From const &f) {return f;
}
//向下转换,基类from指针转换为派生类to指针
template<typename To, typename From>
inline To down_cast(From* f) { if (false) {implicit_cast<From*, To>(0);}#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)assert(f == NULL || dynamic_cast<To>(f) != NULL);
#endifreturn static_cast<To>(f);
}}
Types.h
#ifndef MUDUO_BASE_TYPES_H
#define MUDUO_BASE_TYPES_H#include <stdint.h>
#ifdef MUDUO_STD_STRING
#include <string>
#else // !MUDUO_STD_STRING
#include <ext/vstring.h>
#include <ext/vstring_fwd.h>
#endif///
/// The most common stuffs.
///
namespace muduo
{#ifdef MUDUO_STD_STRING
using std::string;
#else // !MUDUO_STD_STRING
typedef __gnu_cxx::__sso_string string;
#endif// Taken from google-protobuf stubs/common.h
//
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://code.google.com/p/protobuf/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.// Author: kenton@google.com (Kenton Varda) and others
//
// Contains basic types and utilities used by the rest of the library.//
// Use implicit_cast as a safe version of static_cast or const_cast
// for upcasting in the type hierarchy (i.e. casting a pointer to Foo
// to a pointer to SuperclassOfFoo or casting a pointer to Foo to
// a const pointer to Foo).
// When you use implicit_cast, the compiler checks that the cast is safe.
// Such explicit implicit_casts are necessary in surprisingly many
// situations where C++ demands an exact type match instead of an
// argument type convertable to a target type.
//
// The From type can be inferred, so the preferred syntax for using
// implicit_cast is the same as for static_cast etc.:
//
// implicit_cast<ToType>(expr)
//
// implicit_cast would have been part of the C++ standard library,
// but the proposal was submitted too late. It will probably make
// its way into the language in the future.//隐式转换,将from类型转换成to类型
template<typename To, typename From>
inline To implicit_cast(From const &f) {return f;
}// When you upcast (that is, cast a pointer from type Foo to type
// SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts
// always succeed. When you downcast (that is, cast a pointer from
// type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
// how do you know the pointer is really of type SubclassOfFoo? It
// could be a bare Foo, or of type DifferentSubclassOfFoo. Thus,
// when you downcast, you should use this macro. In debug mode, we
// use dynamic_cast<> to double-check the downcast is legal (we die
// if it's not). In normal mode, we do the efficient static_cast<>
// instead. Thus, it's important to test in debug mode to make sure
// the cast is legal!
// This is the only place in the code we should use dynamic_cast<>.
// In particular, you SHOULDN'T be using dynamic_cast<> in order to
// do RTTI (eg code like this:
// if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
// if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
// You should design the code some other way not to need this.//向下转换,基类from指针转换为派生类to指针
template<typename To, typename From> // use like this: down_cast<T*>(foo);
inline To down_cast(From* f) { // so we only accept pointers// Ensures that To is a sub-type of From *. This test is here only// for compile-time type checking, and has no overhead in an// optimized build at run-time, as it will be optimized away// completely.if (false) {implicit_cast<From*, To>(0);}#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)assert(f == NULL || dynamic_cast<To>(f) != NULL); // RTTI: debug mode only!
#endifreturn static_cast<To>(f);
}}#endif
这篇关于base2. Atomic原子操作,Types类型转换的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!