C ++ boost :: thread and automatic container lock

Is there a way to automatically lock the STL container upon access, without the need to lock and release around it?

+3
source share
2 answers

The C ++ standard does not talk about thread safety for STL containers. Officially, an STL implementation may be thread safe, but it is very unusual. If your STL implementation is not thread safe, you will need to “lock and release it” or find another way to coordinate access.

You may be interested in Intel Threading Building Blocks , which includes some thread-safe containers similar to STL containers.

+5
source

After long searches, it seems to do this to create a wrapper around your container. eg:.

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 ...
}
+2
source

Source: https://habr.com/ru/post/1721470/


All Articles