3

有没有办法在访问时自动锁定 STL 容器,而不必在它周围锁定和释放?

4

2 回答 2

5

当前的 C++ 标准没有说明 STL 容器的线程安全性。正式地,STL 实现可能是线程安全的,但这是非常不寻常的。如果您的 STL 实现不是线程安全的,那么您将需要“锁定和释放它”或寻找其他方式来协调访问。

您可能对英特尔的线程构建块感兴趣,其中包括一些类似于 STL 容器的线程安全容器。

于 2009-10-30T05:32:37.530 回答
2

经过大量谷歌搜索,似乎这样做的方法是在容器周围创建一个包装器。例如:

template<typename T>
class thread_queue
{
private:
    std::queue<T> the_queue;
    mutable boost::mutex the_mutex;
    boost::condition_variable the_condition_variable;
public:
    void push(T const& data)
    {
        boost::mutex::scoped_lock lock(the_mutex);
        the_queue.push(data);
        lock.unlock();
        the_condition_variable.notify_one();
    }
    etc ...
}
于 2009-10-30T05:42:16.967 回答