-2

I am using lot of std::queue<uint32_t> Queue on my c++ runtime application. I need to understand, what will be the maximum number of values I can push into the queue and what will happen if I pop_front() with any push_back().

Sometimes my code breaks inside a thread when trying to pop a value.

PostEvent(uint32_t EventUid)
{
    /* Create Event Thread only when 
       first event received (E_RESTART.COLD) */
    if (!isThreadCreated) {
        c_thread::start("event");
        isThreadCreated = true;
    }

    Queue.push_back(EventUid);
}

event_thread::run():

while (isThreadAlive())
{
    while (Queue.size())
    {
        if (!Queue.empty())
        {
            uint32_t EventUid;
            EventUid = Queue[0];
            Queue.pop_front();
        }
    }
}

Also I need to know, can I use data structure like

struct Counter_Elements
{
    uint32_t              eventId;
    std::string           applicationName;
    std::string           functionName;
    std::string           dataName; 
    std::string           dataValue;
    uint64_t              count;
    char                  tag;
};

and create a queue like std::queue<Counter_Elements> CountQueue. If so what will be the max number of counter elements that I can push.

kar
  • 495
  • 1
  • 8
  • 19

1 Answers1

0

The standard containers are only thread-safe for read-only situations. You'll want to use (for example) a mutex to protect the queue while you modify it (pushing and/or popping).

Typically you'd want to start by creating your thread-safe queue, something like this:

template <class T, class Container = std::deque<T>> 
class ts_queue {
    Container c;
    std::mutex m;
public:
    void push(T const &v) { 
       std::lock_guard<std::mutex> l(m);
       c.push_back(v); 
    }

    bool pop(T &v) { 
       std::lock_guard<std::mutex> l(m);

       if (c.empty())
           return false;

       v = c.front();
       c.pop_front();
       return true;
    }
};

This way, only one thread can modify the queue at any given time, keeping the queue safe.

Note that I've changed the signature of pop to one I've found (much) more useful when doing multi-threaded programming. In a typical case, you want to add a time-out to the pop (and maybe the push as well) so if no data is available in a reasonable length of time, you just give up and return false. As it stands now, this does a simplified version of that, returning false if data isn't available immediately.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111