我可以使用这个类包装器对对象进行线程安全访问,并且所需的行为符合 C++11 吗?
琴弦的主要重音:
T* operator->() {
和
T& operator*() {
注意,我知道这里最适合使用 std::atomic<> 作为整数(int),但在这段代码中,我们可以使用任何其他对象而不是 int。
2.0 版通过使用执行指针习语:
#include<thread>
#include<mutex>
#include<memory>
#include<iostream>
#include<vector>
template<typename T>
class safe_obj {
T obj;
mutable std::mutex mtx;
safe_obj(safe_obj<T> &) {}
safe_obj<T>& operator=(safe_obj<T> &) {}
class T_exclusive_lock {
std::unique_lock<std::mutex> xlock;
public:
T*const self;
T_exclusive_lock(T * const s, std::mutex& _mtx)
:self(s), xlock(_mtx) {}
T* operator -> () const {return self;}
operator T&() {return *self;}
friend std::ostream& operator << (std::ostream &stream, T_exclusive_lock &obj) {
stream << obj;
return stream;
}
};
public:
template<typename Types>
safe_obj(Types args) : obj(args )
{ }
T_exclusive_lock operator->() {
return T_exclusive_lock(&obj, mtx);
}
T_exclusive_lock* operator*() {
return &T_exclusive_lock(&obj, mtx);
}
};
int main() {
safe_obj<std::shared_ptr<int> > safe_int( std::make_shared<int>(10) );
auto lambda = [&safe_int]() {
std::cout << safe_int->use_count() << std::endl; // is that thread-safe?
std::cout << *safe_int << std::endl; // is that thread-safe?
std::cout << *safe_int->get() << std::endl; // is that thread-safe?
};
std::vector<std::thread> thr_grp;
for(size_t i = 0; i < 10; ++i) thr_grp.emplace_back(std::thread(lambda));
for(auto &i : thr_grp) i.join();
int b; std::cin >> b;
return 0;
}