1

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I found real problem. Thread object destroyed before this loop starts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.