首页 > 代码库 > ACE_linux:读写锁
ACE_linux:读写锁
1.涉及类
ACE_RW_Thread_Mutex //ACE读写锁
ACE_Read_Guard //ACE加读锁
ACE_Write_Guard //ACE加写锁
ACE_Thread_Manager //ACE线程管理
2.简介
ACE读/写锁
读/写锁与互斥体相类似。例如,获取读/写锁的线程也必须释放它。多个线程可同时获取一个读/写锁用于读,但只有一个线程可以获取该锁用于写。当互斥体保护的资源用于读远比用于写要频繁时,读/写互斥体有助于改善并发的执行。
ACE线程库提供了一个叫作ACE_RW_Mutex的类,在C++封装类中可移植地实现了读/写锁的语义。读/写锁将优先选择权给写。因而,如果有多个读和一个写在锁上等待,写将会首先获取它。
3.示例代码
1 #include <iostream> 2 #include "ace/Thread_Manager.h" 3 #include "ace/Guard_T.h" 4 #include "ace/OS_NS_time.h" 5 6 using namespace std; 7 ACE_RW_Thread_Mutex mutex; 8 9 ACE_THR_FUNC_RETURN ThreadFunRead(void *arg) 10 {11 ACE_thread_t threadId=ACE_Thread_Manager::instance()->thr_self();12 13 ACE_Read_Guard<ACE_RW_Thread_Mutex> guard(mutex);14 cout<<"Thread ReadLock begin NO:"<<threadId<<endl;15 16 17 //ACE_OS::sleep(4);18 cout<<"Thread ReadLock end NO:"<<threadId<<endl;19 return NULL; 20 } 21 ACE_THR_FUNC_RETURN ThreadFunWrite(void *arg) 22 {23 ACE_thread_t threadId=ACE_Thread_Manager::instance()->thr_self();24 25 ACE_Write_Guard<ACE_RW_Thread_Mutex> guard(mutex);26 cout<<"Thread WriteLock begin NO:"<<threadId<<endl;27 28 ACE_OS::sleep(1);//休眠1s29 cout<<"Thread WriteLock end NO:"<<threadId<<endl;30 return NULL; 31 }32 33 int main(int argc, char *argv[]) 34 { 35 //1000纳秒=1ms36 timespec_t t;37 t.tv_sec=0;t.tv_nsec=1000;38 39 ACE_Thread_Manager* pThrMgr = ACE_Thread_Manager::instance();40 //依次一读一写依次3个循环,结果显示是此读写锁写优先。即:加锁等待队列里写操作永远在读前面!41 for(int i=0;i<4;i++)42 {43 pThrMgr->spawn((ACE_THR_FUNC)ThreadFunRead); 44 ACE_OS::nanosleep (&t);45 pThrMgr->spawn((ACE_THR_FUNC)ThreadFunWrite); 46 ACE_OS::nanosleep (&t);47 }48 pThrMgr->wait();49 50 return 0; 51 }
4.示例运行结果
$ ./ttThread ReadLock begin NO:140015069234944Thread ReadLock end NO:140015069234944Thread WriteLock begin NO:140015058745088Thread WriteLock end NO:140015058745088Thread WriteLock begin NO:140015037765376Thread WriteLock end NO:140015037765376Thread WriteLock begin NO:140015016785664Thread WriteLock end NO:140015016785664Thread WriteLock begin NO:140014658778880Thread WriteLock end NO:140014658778880Thread ReadLock begin NO:140015048255232Thread ReadLock end NO:140015048255232Thread ReadLock begin NO:140015027275520Thread ReadLock end NO:140015027275520Thread ReadLock begin NO:140015006295808Thread ReadLock end NO:140015006295808
5.Makefile
#binTHE_INCLUDE = -I./ -I${ACE_ROOT}/THE_LIBPATH = -L./ -L${ACE_ROOT}/lib/THE_LIB = -g -D_DEBUG_ -lACE# -lxtiCFLAGS = ${THE_LIB} ${THE_INCLUDE} ${THE_LIBPATH}CC=g++SRC=$(wildcard *.cpp)OBJ=$(addprefix ./, $(addsuffix .o, $(basename $(SRC))))TARGET=ttall: $(TARGET)$(TARGET): $(SRC) $(CC) -o $@ $^ $(CFLAGS) @echo make all done%.o: %.cpp $(CC) $(CFLAGS) -o $@ -c $<clean: rm -f $(TARGET) $(OBJ)
ACE_linux:读写锁
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。