Access to a member variable of a thread upstream object

I use an object to start a boost stream, and it has some public member variables that I modify in the stream (in the () statement). How can I access the member variables of an object outside the stream?

I tried to use a mutex (defined in the class of objects), which is locked both in the operator () of the object and outside, but it does not work.

Here's the code for the stream object:

struct Mouse { int x, y; string port; boost::mutex mutex; Mouse(const string& p) : port(p) { x = y = 0; } Mouse(const Mouse& m) : mutex() { x = mx; y = my; port = m.port; } void operator()() { ifstream ifs; ifs.open (port.c_str(), ios::binary ); if (!ifs.is_open()) { cout << "Impossible d'ouvrir " << port.c_str() << "\n"; exit(0); } while (true) //modify x, y in infinit loop { char buf[3]; ifs.read(buf, 3); unsigned char * msg = (unsigned char *) buf; unsigned char xsign = (msg[0]>>4) & 1; unsigned char ysign = (msg[0]>>5) & 1; unsigned char always1 = (msg[0]>>3) & 1; short dx = msg[1] - 256*xsign; short dy = msg[2] - 256*ysign; { boost::mutex::scoped_lock lock(mutex); x += abs(dx); y += dy; } } } }; 

And this is where I try to access the x and y variables of the mouse:

  { boost::mutex::scoped_lock leftlock(leftMouse.mutex); xLeft = leftMouse.x; yLeft = leftMouse.y; } { boost::mutex::scoped_lock rightlock(rightMouse.mutex); xRight = rightMouse.x; yRight = rightMouse.y; } cout << xRight << " " << yRight << endl; //this always prints 0 0 
+4
source share
2 answers

boost::thread copies the passed stream function to internal memory, so if you start your stream like this, the stream will work with another copy of mouse :

 int main() { Mouse mouse("abc.txt"); boost::thread thr(mouse); // thr gets a copy of mouse ... // thread changes it own copy of mouse ... } 

You can use boost::ref to pass a reference to an existing object:

  Mouse mouse("abc.txt"); boost::thread thr(boost::ref(mouse)); // thr gets a reference of mouse 

In this case, thr will modify the global mouse object, but you must make sure that the mouse does not go out of scope or is destroyed otherwise before the completion of thr .

+10
source

OK, now I see it more clearly. Some tips regarding your code:

  • Do not expose internal mutexes.
  • Record access operations that lock and unlock mutexes. Thus, you do not need to relay the user of your class to effectively lock (and unlock) the mutex.
  • Read the data from the file before the stream. Probably reading is blocked, or too slow for another thread to receive data. If you read the data earlier, and then start the stream, all the data will be read by the clients access time to the stream data.
0
source

All Articles