I am using queue for communication between two threads ( one just producing instance of custom class and pushes pointer to queue, other read from queue pointer on custom class and make some calculations). How to make push and pop on queue atomic, how to lock those operations ?( I cannot use C++11 standard )
Probably the most portable non-C++11 locking mechanism is are the synchronisztion types from the Boost.Thread library. In particular the mutex class gives you a simple lockable object for giving exclusive access to a resource. For example:
#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 this is quite similar to the C++11 std::mutex
class, which will make conversion quite straightforward if you decide to use that instead.
Here is a pseudo code:
// Thread A
mutex.lock();
q.push();
mutex.unlock();
// Thread B
mutex.lock();
q.pop();
mutex.unlock();
If you're using boost, you may try it's mutex class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With