开发者

C++ segmentation fail on vector.erase()

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;
    }
};

the开发者_JAVA技巧n 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?


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 a vector.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜