Muduo库
MutexLock
class MutexLock : boost::noncopyable
{
public:
MutexLock():holder_(0){
pthread_mutex_init(&mutex_,NULL);
}
~MutexLock(){
pthread_mutex_destroy(&mutex_);
}
bool isLockByThisThread(){
return holder_ == pthread_self();
//原本是holder_ == CurrentThread::tid();
}
void assertLocked(){
assert(isLockByThisThread());
}
void lock(){
pthread_mutex_lock(&mutex_);
holder_ = pthread_self();
//如果两行反了,当前线程还没拿上锁呢,isLockByThisThread就会返回错误的结果了
// 原本是holder_ = CurrentThread::tid();
}
void unlock(){
holder_ = 0;
pthread_mutex_unlock(&mutex_);
//同上
}
pthread_mutex_t* getPhreadMutex(){
return &mutex_;
}
private:
pthread_mutex_t mutex_;
pid_t holder_;
};
}
class MutexLockGuard : boost::noncopyable{
public:
explicit MutexLockGuard(MutexLock& mutex):mutex_(mutex){
mutex.lock();
}
~MutexLockGuard(){
mutex_.unlock();
}
private:
MutexLock mutex_;
};
有报错
条件变量
class Condition :boost::noncopyable
{
public:
explicit Condition(MutexLock& mutex):mutex_(mutex) {
pthread_cond_init(&pcond_,NULL);
}
~Condition(){
pthread_cond_destroy(&pcond_);
}
void wait(){
pthread_cond_wait(&pcond_,mutex_.getPthreadMutex());
}
void notify(){
pthread_cond_signal(&pcond_);
}
void notifyall(){
pthread_cond_broadcast(&pcond_);
}
private:
MutexLock& mutex_;
pthread_cond_t pcond_;
};
线程安全的读写操作
class Foo
{
public:
Foo();
~Foo();
private:
int value;
};
typedef std::vector<Foo> Foolist;
using FooListPtr = std::shared_ptr<Foolist>;
std::mutex mutex_;
FooListPtr g_foos;
//遍历
void travels(){
FooListPtr foos;
{
std::lock_guard<std::mutex> lockguard(mutex_);
foos = g_foos;
assert(!g_foos.unique());
}
for(auto it = foos->begin();it!= foos->end()){
it.doit();
}
}
void post(const Foo& f){
std::lock_guard<std::mutex> lockguard(mutex_);
if(!g_foos.unique()){
//如果不止一个人正在使用g_foos,那么将g_foos重置
g_foos.reset(new Foolist(*g_foos));
//Replaces the managed object with an object pointed to by ptr.
//保证在写的时候g_foos只有当前线程在调用
}
assert(g_foos.unique());
g_foos->push_back(f);
}
浙公网安备 33010602011771号