Getting Started 05 Network Programming

These days because of work needs to learn multithreaded programming, using the thread pool written a small tool for callbacks network library, multithreading understanding deepened layer of understanding. We found that the use of multi-threading understanding, understanding these small components, is also very important. Work was interrupted, net direct reading module a little more difficult, going to read from the module from the base.
class noncopyable{} //把赋值构造和赋值操作直接删除,默认构造和析构使用默认操作。
class copyable{} //把构造和析构设置默认,其余不变,编译器设置

//编译器本身提供的原子操作
type __sync_fetch_and_add (type *ptr, type value, ...)
type __sync_fetch_and_sub (type *ptr, type value, ...)
type __sync_fetch_and_or (type *ptr, type value, ...)
type __sync_fetch_and_and (type *ptr, type value, ...)
type __sync_fetch_and_xor (type *ptr, type value, ...)
type __sync_fetch_and_nand (type *ptr, type value, ...)


type __sync_add_and_fetch (type *ptr, type value, ...)
type __sync_sub_and_fetch (type *ptr, type value, ...)
type __sync_or_and_fetch (type *ptr, type value, ...)
type __sync_and_and_fetch (type *ptr, type value, ...)
type __sync_xor_and_fetch (type *ptr, type value, ...)
type __sync_nand_and_fetch (type *ptr, type value, ...)
//这两组函数的区别在于第一组返回更新前的值,第二组返回更新后的值。

bool __sync_bool_compare_and_swap (type *ptr, type oldval type newval, ...)
type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...)
这两个函数提供原子的比较和交换,如果*ptr == oldval,就将newval写入*ptr,
第一个函数在相等并写入的情况下返回true.
第二个函数在返回操作之前的值。

type __sync_lock_test_and_set (type *ptr, type value, ...)
   将*ptr设为value并返回*ptr操作之前的值。

void __sync_lock_release (type *ptr, ...)
     将*ptr置0
AtomicIntegerT 原子类的实现利用了gcc提供原子操作,在c++11中有了std::atomic<int> 类
template <typename T>
class AtomicIntegerT:noncopyable{
public:
    T get() {
        return __sync_val_compare_and_swap(&value_, 0, 0);
    }
    T getAndAdd(T x) {
       return __sync_fetch_and_add(&value_, x);
    }
    T addAndGet(T x) {
       return getAndAdd(x) + x;
    }
    T incrementAndGet() {
       return addAndGet(1);
    }
    T decrementAndGet() {
       return addAndGet(-1);
    }
     void add(T x) {
       getAndAdd(x);
     }
     void increment() {
       getAndAdd(1);
     }
     void decrement() {
             getAndAdd(-1);
     }
     T getAndSet(T x) {
          return __sync_lock_test_and_set(&value_, x);
     }
private:
   volatile T value_;  初始化为0
}
typedef detail::AtomicIntegerT<int32_t> AtomicInt32;
typedef detail::AtomicIntegerT<int64_t> AtomicInt64;

Guess you like

Origin www.cnblogs.com/aiqingyi/p/11306521.html