读书人

同一函数或者加锁可能不加锁使用

发布时间: 2013-10-29 12:07:57 作者: rapoo

同一函数可能加锁可能不加锁使用

当一个函数可能在加锁状态下使用,也可能在不加锁状态下使用时,将函数分割为两个版本:加锁版本,不加锁版本

如下例子:

#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()

读书人网 >编程

热点推荐