#ifndef _RWLOCK_H_ #define _RWLOCK_H_ struct rwlock { int write; int read; }; static inline void rwlock_init(struct rwlock *lock) { lock->write = 0; lock->read = 0; } static inline void rwlock_rlock(struct rwlock *lock) { for (;;) { while(lock->write) { __sync_synchronize(); } __sync_add_and_fetch(&lock->read,1); if (lock->write) { __sync_sub_and_fetch(&lock->read,1); } else { break; } } } static inline void rwlock_wlock(struct rwlock *lock) { while (__sync_lock_test_and_set(&lock->write,1)) {} while(lock->read) { __sync_synchronize(); } } static inline void rwlock_wunlock(struct rwlock *lock) { __sync_lock_release(&lock->write); } static inline void rwlock_runlock(struct rwlock *lock) { __sync_sub_and_fetch(&lock->read,1); } #endif
上面这段是skynet中的运用
// 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) { } // uncomment if you need copying and assignment // // AtomicIntegerT(const AtomicIntegerT& that) // : value_(that.get()) // {} // // AtomicIntegerT& operator=(const AtomicIntegerT& that) // { // getAndSet(that.get()); // return *this; // } 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() { incrementAndGet(); } void decrement() { decrementAndGet(); } T getAndSet(T newValue) { return __sync_lock_test_and_set(&value_, newValue); } private: volatile T value_; }; } typedef detail::AtomicIntegerT<int32_t> AtomicInt32; typedef detail::AtomicIntegerT<int64_t> AtomicInt64; } #endif // MUDUO_BASE_ATOMIC_H
这一段是在muduo中的运用。
原文:http://no001.blog.51cto.com/1142339/1357297