如何使stl线程安全 [英] how to make stl thread safe

查看:108
本文介绍了如何使stl线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 template< typename container =  > 
锁定{
public
// 已被省略
锁定( const 容器和放大器;容器)
:c(容器){
getMutexFor(c);
}

~Lock(){
releaseMutexFor(c);
}
private
const Container& C;
};





如何实现releaseMutexFor和getMutexFor?

解决方案

你的想法很吸引人,但我猜它不会起作用。要使互斥锁有效,它必须是它应该保护的对象的一部分或至少与其相关联。所以你不希望每个Lock对象有一个互斥锁,而是每个容器对象有一个互斥锁。



一个可能的机制是在你的锁类中分配一个地图将每个容器对象与Lock对象帮助的专用互斥锁相关联。但是,这种方法不会真正起作用,因为在销毁容器时不会通知您的Lock对象。因此,随着时间的推移,你的地图会变得越来越大。



我看不出它是如何有效地完成你正在尝试的。


为什么不使用 C ++ 11 锁?例如,请参阅 C ++ 11线程,锁和条件变量 [ ^ ]

template<typename container="">
class Lock {
public:
    // have been omitted
    Lock(const Container& container)
        : c(container){
            getMutexFor(c);
    }
 
    ~Lock() {
        releaseMutexFor(c);
    }
private:
    const Container& c;
};



How to realize the releaseMutexFor and getMutexFor?

解决方案

Your idea is intriguing, but I guess it won't work. For a mutex to be effective it has to be part of or at least associated to the object it is supposed to protect. So you don't want to have one mutex per Lock object, but one mutex per container object.

A possible mechanism would be to allocate a map in you lock class that associates each container object with a dedicated mutex that is help by the Lock object. However, this approach won't really work, because your Lock object will not be informed when a container is destroyed. And hence your map will get bigger and bigger over time.

I don't see how it could be effectively done what you are trying.


Why don't you use C++11 locks? See, for instance C++11 threads, locks and condition variables[^].


这篇关于如何使stl线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆