的成员变量我使用一个对象来启动升压线程,它有我在线程修改(在()运算符)某些公共成员变量。我如何从线程外部访问对象的成员变量?访问升压线程对象
我尝试使用既在对象的运算符(),并从外面锁上互斥(在对象的类中定义),但它似乎并没有工作。
这里的线程对象代码:
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;
}
}
}
};
而这正是我试图访问该鼠标的变量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
请问您可以发布一些代码,看看究竟是如何工作? – 2009-02-23 23:29:06