c++ - 使用线程时 Linux 事件轮询不起作用

标签 c++ c linux multithreading linux-device-driver

我有以下代码来池事件数据(基于此 Multitouch Protocol )。为了不延迟我的应用程序,我决定使用线程。问题是线程卡在它包含的行中:
read(_touchEvent, &ie, sizeof(ie));
我尝试在它周围放置 printf 语句,并在它之前而不是之后打印它。

void TouchDriverAdapter::_poolData(){
  // Refer to kernel multitouch.
  struct input_event ie;
  read(_touchEvent, &ie, sizeof(ie));
  if(ie.code == ABS_MT_SLOT){
    _currentSlot = ie.value;
  }else if(ie.code == SYN_REPORT){
    _numContacts = _currentSlot;
    // Transfer cached data to vector.
    for(int i = 0; i <= _numContacts; i++){
      _touchData[i] = _touchDataTemp[i];
    }
  }else{
    if(ie.code == ABS_X){   
      _touchDataTemp[_currentSlot].x = ie.value;
      printf("%i\n", ie.value);
    }else if(ie.code == ABS_Y){
      _touchDataTemp[_currentSlot].y = ie.value;
    }
  }

  _lastCode = ie.code;
}

这是我创建线程的单例。

// Singleton.
TouchDriverAdapter* TouchDriverAdapter::getInstance(){
  if(_instance->_touchEvent < 0){
    return NULL;
  }else if(_running == false){
    int result = pthread_create( TouchDriverAdapter::_thread, NULL, 
                 TouchDriverAdapter::_runThread, 
                 (void*)&_instance);
    if(result != 0){
      printf("Error: %i, Failed to create a thread.\n", result);
      return NULL;
    }
    _running = true;
    pthread_detach( *TouchDriverAdapter::_thread);
    //pthread_join( *TouchDriverAdapter::_thread, NULL);
    return TouchDriverAdapter::_instance;
  }else if(_running == true){
    return _instance;
  }
}

当我不使用线程时,这仍然有效,但我一次只能读取数据段,这对于多点触控应用程序来说有点无用。

最佳答案

我上面使用的是 POSIX pthread_t,这是一个没有考虑类而编写的库。另一方面,C++ 的 std::thread 使此事件轮询完美地工作,我只需添加 -std=c++11。

关于c++ - 使用线程时 Linux 事件轮询不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20756758/

相关文章:

c++ - 调试程序集时,如何在 VS2019 watch 窗口中将内存地址转换为用户定义的类型?

c++ - Windows 类 NCurses 系统

linux - OpenSSL 以静态方式链接 libcrypto.a

linux - 我如何在 Windows 上使用 escapeshellarg() 而不是 "aimed for Linux"(反之亦然)?

c++ - CRichEditCtrl 及其文本内容

linux - bash 可以用来直接与硬件通信吗?

c# - 如何使用 WCHAR* 在消息框中显示来自 C# 的 C 函数

C++ - 如何将元素从 std::priority_queue 复制到 std::vector

c - 读取结构文件时出现段错误

c - 错误: expected expression before ‘void’