How to push and pop in an atom queue, how to block these operations?

I use a queue to communicate between two threads (one simply instantiates a user class and presses the pointer to the queue, the other reads from the queue pointer to the user class and does some calculations). How to push and pop on queue atomic, how to block these operations? (I can not use the standard C ++ 11)

+6
source share
2 answers

Probably the most portable locking mechanism other than C ++ 11 is the synchronization of the Boost.Thread library . In particular, the mutex class gives you a simple lockable object to provide exclusive access to a resource. For instance:

#include <boost/thread/mutex.hpp> #include <queue> template <typename T> class locking_queue { public: void push(T const & value) { boost::mutex::scoped_lock lock(mutex); queue.push(value); } bool pop(T & value) { boost::mutex::scoped_lock lock(mutex); if (queue.empty()) { return false; } else { value = queue.front(); queue.pop(); return true; } } private: std::queue<T> queue; boost::mutex mutex; }; 

Another advantage is that it is very similar to the C ++ 11 std::mutex , which will make the conversion pretty simple if you decide to use it instead.

+8
source

Here is the pseudo code:

 // Thread A mutex.lock(); q.push(); mutex.unlock(); // Thread B mutex.lock(); q.pop(); mutex.unlock(); 

If you use boost, you can try the mutex class.

+3
source

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


All Articles