Al.*_*Al. 4 c++ multithreading boost
我正在使用一个对象来启动boost线程,它有一些我在线程中修改的公共成员变量(在()运算符中).如何从线程外部访问对象的成员变量?
我尝试使用在对象的operator()和外部锁定的互斥锁(在对象的类中定义),但它似乎不起作用.
这是线程对象代码:
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 = m.x; y = m.y; 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;
}
}
}
};
Run Code Online (Sandbox Code Playgroud)
这是我尝试访问鼠标的x和y变量的地方:
{
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
Run Code Online (Sandbox Code Playgroud)
sth*_*sth 10
boost::thread将传递的线程函数复制到内部存储器,因此如果您启动这样的线程,该线程将在不同的副本上运行mouse:
int main() {
Mouse mouse("abc.txt");
boost::thread thr(mouse); // thr gets a copy of mouse
...
// thread changes it's own copy of mouse
...
}
Run Code Online (Sandbox Code Playgroud)
您可以使用boost::ref传递对现有对象的引用:
Mouse mouse("abc.txt");
boost::thread thr(boost::ref(mouse)); // thr gets a reference of mouse
Run Code Online (Sandbox Code Playgroud)
在这种情况下,thr将修改全局mouse对象,但您必须确保mouse不会超出范围或在thr完成之前被销毁.