我正在使用一个对象来启动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 * …Run Code Online (Sandbox Code Playgroud) 我们试图从连接到linux盒子的2 usb鼠标中读取数据(这些数据用于机器人的测距/定位).所以我们需要不断地从每只鼠标中读取它移动了多少.问题是当鼠标没有移动时,它不会发送任何数据,因此我们从中获取数据块的文件流,因此程序无法进行里程计算(其中涉及速度的时间测量) .
有没有办法在输入流上设置超时(我们在C++中使用ifstream并从/ dev/input/mouse读取),这样我们就可以知道鼠标何时不移动,而不是等待要收到的活动?或者我们需要搞乱线程(arggh ......)?欢迎任何其他建议!
提前致谢!