C++读写锁

读写锁

class Student {
public:
	void SetTeacher(const Teacher &teacher) {
        std::lock_guard<std::mutex> lock(teacherMutex_);
		teacher_ = teacher;
	}
	
	Teacher GetTeacher(const Teacher &teacher) const {
		std::lock_guard<std::mutex> lock(teacherMutex_);
		return teacher_;
	}

private:
	Teacher teacher_;
	mutable std::mutex teacherMutex_; // Mutex for teacher.
}

以上这段代码功能没有问题,但是如果读操作很频繁的话,由于读操作不能并发,会导致性能低下。

锁的意义在于保护共享变量, 我们只要保证读的时候不会发生写操作就可以了,多个读操作并发应该允许。

上面那段代码可以改为:

class Student {
public:
	void SetTeacher(const Teacher &teacher) {
        std::unique_lock<std::shared_mutex> lock(teacherMutex_);
		teacher_ = teacher;
	}
	
	Teacher GetTeacher(const Teacher &teacher) const {
		std::shared_lock<std::shared_mutex> lock(teacherMutex_);
		return teacher_;
	}

private:
	Teacher teacher_;
	mutable std::shared_mutex teacherMutex_; // Mutex for teacher.
}

你可能感兴趣的:(C++)