对于一个类,想要在每个线程种有且只有一个实例对象,且线程之间不共享该实例,可以按照单例模式的写法,同时使用C++11提供的thread_local关键字实现。
在单例模式的基础上,使用thread_local关键字修饰单例的instance,保证该静态成员在一个线程创建时创建单独的副本。
class A {
public:
static std::shared_ptr<A> getInstance() {
if (!instance) {
std::lock_guard<std::mutex> lock(mutex);
if (!instance) {
instance = std::shared_ptr

最低0.47元/天 解锁文章
1266

被折叠的 条评论
为什么被折叠?



