我的程序中有 vector 问题。我发现了很多类似的问题,但没有解决方案。此代码在新线程中:
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 是一个 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 的情况下保持指向它的指针?
最佳答案
猜测:您没有任何锁来保护您的 actions
队列,是吗?
当从多个线程访问相同的数据结构时,您需要使用锁或其他同步结构来防止同时访问,否则可能会导致奇怪的事情(崩溃或更糟)。
当您这样做时,您可能应该使用条件变量来避免每 20 毫秒醒来一次,即使无事可做。并使用 deque
作为队列,而不是 vector
。
关于vector.erase() 上的 C++ 分段失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5495514/