同一函数可能加锁可能不加锁使用
当一个函数可能在加锁状态下使用,也可能在不加锁状态下使用时,将函数分割为两个版本:加锁版本,不加锁版本
如下例子:
#include<iostream>#include<unistd.h>//#include<pthread.h>#include<string>using namespace std;class test{ public: void process(){ pthread_mutex_lock(&mutex); cout<<"process()"<<endl; print(); pthread_mutex_unlock(&mutex); } void print(){//不加锁版本 cout<<"print()"<<endl; } void printWithLock(){//加锁版本 pthread_mutex_lock(&mutex); print(); pthread_mutex_unlock(&mutex); } test(){ pthread_mutex_init(&mutex,NULL); } private: pthread_mutex_t mutex;};int main(){ test one; one.process(); return 0;}
process()
print()