c++;无推送的队列弹出 我在C++运行时应用程序中使用了大量的。 我需要了解,我可以推送到队列中的值的最大数量是多少,如果我使用任何后推(),会发生什么情况
有时,我的代码在试图弹出一个值时在线程内部中断c++;无推送的队列弹出 我在C++运行时应用程序中使用了大量的。 我需要了解,我可以推送到队列中的值的最大数量是多少,如果我使用任何后推(),会发生什么情况,c++,data-structures,queue,C++,Data Structures,Queue,有时,我的代码在试图弹出一个值时在线程内部中断 PostEvent(uint32_t EventUid) { /* Create Event Thread only when first event received (E_RESTART.COLD) */ if (!isThreadCreated) { c_thread::start("event"); isThreadCreated = true; } Queu
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);
}
事件线程::运行():
我还需要知道,我可以像这样使用数据结构吗
struct Counter_Elements
{
uint32_t eventId;
std::string applicationName;
std::string functionName;
std::string dataName;
std::string dataValue;
uint64_t count;
char tag;
};
并创建一个类似于
std::queue CountQueue
的队列。如果是这样,我可以推送的计数器元素的最大数量是多少。对于只读情况,标准容器是线程安全的。例如,在修改队列(推送和/或弹出)时,需要使用互斥来保护队列
通常,您希望从创建线程安全队列开始,如下所示:
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;
}
};
模板
类ts_队列{
容器c;
std::互斥m;
公众:
无效推力(T常数和v){
标准:锁紧装置l(m);
c、 推回(v);
}
布尔波普(T&v){
标准:锁紧装置l(m);
if(c.empty())
返回false;
v=c.前();
c、 pop_front();
返回true;
}
};
这样,在任何给定时间只有一个线程可以修改队列,从而保证队列的安全
请注意,我已将
pop
的签名更改为我发现在进行多线程编程时更有用的签名。在典型的情况下,您希望向pop(也可能是推送)添加一个超时,因此如果在合理的时间长度内没有可用的数据,您只需放弃并返回false即可。目前,这是一个简化版本,如果数据不能立即使用,则返回false。建议对该队列进行互斥保护。这看起来像是并发问题。您熟悉互斥量和条件变量之类的概念吗?
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;
}
};