I am trying to use c++ queue. I know queue element can be accessed by existing threads, but I want to use same queue element. It will be used by all threads, e.g: same video frame I want to use between thread1 and thread2.

Once it's processed by two threads I want to pop next video frame. I know threads will access individual elements (queue element 1 by thread1 and queue element2 by thread2), but I want to access queue element 1 by both threads. I am unable to lock single buffer for both threads.

Please help me to share same queue element between threads.

1 Answers

Ted Lyngmo On Best Solutions

You could put each frame in an envelope containing a counter that you decrease every time the queue is pop:ed. When the counter reaches zero, you remove the element. Example:

struct envelope_t {
    int count;
    frame_t frame;
    envelope_t(const frame_t& f) : count(2), frame(f) {}

class myqueue {
    std::queue<envelope_t> data;
    std::mutex mtx_data;
    std::condition_variable cv_data;

    template<class... Args>
    decltype(auto) emplace(Args&&... args) {
        std::lock_guard<std::mutex> lock(mtx_data);
        auto rv = data.emplace(std::forward<Args>(args)...);
        return rv;
    frame_t pop() {
        std::unique_lock<std::mutex> lock(mtx_data);
        while(data.size() == 0) cv_data.wait(lock);
        if(--data.front().count) {
            return data.front().frame;
        } else {
            auto msg = std::move(data.front().frame);
            return msg;