C++ vector.erase() 上的分段失败
我的程序中的向量有问题。我发现了很多类似的问题,但没有解决方案。此代码位于新线程中:
while(status == RUN){
msleep(20);
while(status != DESTROY && (!actions.empty()) ){
item = actions.begin();
(*item)();
cout<< "try remove the action!\n";
item=actions.erase(actions.begin());
cout << "everything ok!\n";
}
}
输出为:
action!
try remove the action!
Segmentation fault
actions is a vector<行动>
struct action{
string query;
long size;
void operator()(){
cout << "action!\n";
}
};
更新
真正的问题是:具有此方法的结构已经被破坏。
class mthread{
...
deque<action> actions;
...
operator(){
(loop above)
}
};
class mthread_holder{
mthread* mt;
operator()(){
(*mt)();
}
mthread_holder(mthread *p){
mt = p;
}
};
然后我只是使用:
threads.back().thrd = new boost::thread(mthread_holder(mthrd));
我想,我需要更安全地存储它
如何在线程中存储可调用对象并在没有 boost::bind 的情况下保持指向它的指针?
I have a problem with vector in my program. I found many similar problems but no solution. This code is in new thread:
while(status == RUN){
msleep(20);
while(status != DESTROY && (!actions.empty()) ){
item = actions.begin();
(*item)();
cout<< "try remove the action!\n";
item=actions.erase(actions.begin());
cout << "everything ok!\n";
}
}
the output is:
action!
try remove the action!
Segmentation fault
actions is a vector< action>
struct action{
string query;
long size;
void operator()(){
cout << "action!\n";
}
};
update
The real problem is: struct with this method already destroyed.
class mthread{
...
deque<action> actions;
...
operator(){
(loop above)
}
};
class mthread_holder{
mthread* mt;
operator()(){
(*mt)();
}
mthread_holder(mthread *p){
mt = p;
}
};
then I just use:
threads.back().thrd = new boost::thread(mthread_holder(mthrd));
I think, I need to store it more safely
How can i store the callable in the thread and hold pointer to it without boost::bind?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
猜测:您没有任何锁来保护您的
actions
队列,是吗?当从多个线程访问相同的数据结构时,您需要使用锁或其他同步结构来防止同时访问,否则可能会导致奇怪的事情(崩溃或更糟)。
当您这样做时,您可能应该使用条件变量来避免每 20 毫秒醒来一次,即使没有什么可做的。并使用
deque
作为队列,而不是vector
。At a guess: You don't have any locks protecting your
actions
queue, do you?When accessing the same data structure from multiple threads, you need to use locks or other synchronization constructs to protect against simultaneous access, or weird things (crashes, or worse) can result.
While you're at it, you should probably be using a condition variable to avoid waking up every 20ms even if there's nothing to do. And use a
deque
for a queue, not avector
.