说三道四 > 文档快照
HTML文档下载 WORD文档下载 PDF文档下载
/hpp file#include <atomic>#ifndef ns_mutex_header_#define ns_mutex_header_namespace ns{ struct mutex { mutex(); void req(int is_read)volatile; void unreq(int is_read)volatile; inline void req_read(){req(1);} inline void req_write(){req(0);} inline void unreq_read(){unreq(1);} inline void unreq_write(){unreq(0);} struct enter { enter(mutex* ths_,int is_read_=1):ths(ths_),is_read(is_read_){ths->req(is_read);} ~enter(){ths->unreq(is_read);} private: mutex* ths; int is_read; }; private: std::atomic<uint32_t> read_flags,write_flags; };};#endif//ns_mutex_header_#include "ns_mutex.h"#include <unistd.h>namespace ns{ mutex::mutex() { write_flags=read_flags=0; } void mutex::req(int is_read)volatile { if(is_read) { again_read: while(write_flags!=0)usleep(100); ++read_flags; if(write_flags!=0) { --read_flags; goto again_read; } } else { uint32_t e(0); while(!write_flags.compare_exchange_strong(0,1,e,1))e=0,usleep(100); while(read_flags!=0)usleep(100); } } void mutex::unreq(int is_read)volatile { if(is_read)--read_flags; else --write_flags; }};