I wrapped my mind around this, yet can not find the error. Could anyone help me where I did bad programming.
One boost::thread
receives strings
over a socket, splits them to vector<string>
and sorts them into the right variable inside shared class
. Other threads read from there. I tried to make it thread safe via mutex as shown here.
I appreciate any help, even small hints :)
This is how the program terminates:
Looping...<enter to exit>
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted (core dumped)
And this is the corresponding file. It is entangled with ROS, but that part shouldn't be the verdict.
class shared
{
public:
shared() : count(0) {/*emp. body*/ } //constructor
void setvec(vector<string> &strVec, int type){
boost::upgrade_lock<boost::shared_mutex> lock(mtx);
boost::upgrade_to_unique_lock<boost::shared_mutex> uniqueLock(lock);
switch(type) {
case 1: typ1acc = strVec; setsensor[0] = true; break;
case 2: typ2mag = strVec; setsensor[1] = true; break;
case 3: typ3 = strVec; setsensor[2] = true; break;
}/**/
}
vector<string> getvec(int type) {
boost::shared_lock<boost::shared_mutex> lock(mtx);
switch(type) {
case 1: tmp = typ1acc; break;
case 2: tmp = typ2mag; break;
case 3: tmp = typ3; break;
}
return tmp;
}
private:
boost::shared_mutex mtx;
vector<string> tmp;
vector<string> typ1acc;
vector<string> typ2mag;
vector<string> typ3;
};
shared c; //class object
Class is called from multiple boost::threads:
//socket function which sorts vectors into shared class
//this happens from one boost::thread
int type; //key sort by sensor type
vector<string> strVec;
c.setvec(strVec,type);
//multiple boost::threads call this to read the vectors
//this happens from multiple boost::thread
strVec = c.getvec(type);