c ++ 11将基于pthread的代码更新为std :: thread或boost :: thread

时间:2015-12-07 20:01:23

标签: multithreading c++11

我有以下代码,我想更新,以便更方便,c ++ 11友好。但是,我不知道如何替换pthread调用。我可以使用std :: this_thread :: get_id()来获取线程ID,但无法判断该线程是否仍然存在。

  pthread_t activeThread = 0;

  pthread_t getCurrentThread() {
    return pthread_self();
  }

  bool isActiveThreadAlive() {
    if(activeThread == 0) {
      return false;
    }
    return pthread_kill(activeThread, 0) != ESRCH;
  }

潜在的std :: thread版本......

  std::thread::id activeThread = std::thread::id();

  std::thread::id getCurrentThread() {
    return std::this_thread::get_id();
  }

  bool isActiveThreadAlive() {
    if(activeThread == std::thread::id()) {
      return false;
    }
    return pthread_kill(activeThread, 0) != ESRCH;// <--- need replacement!!!
  }

代码真正需要做的是知道线程是否已经死于异常或导致其终止而不释放对象的其他错误。如下所示...

std::unique_lock<std::mutex> uLock = getLock();
while (activeThread != 0) {
  if (threadWait.wait_for(uLock, std::chrono::seconds(30)) == std::cv_status::timeout) {
    if (!isActiveThreadAlive()) {
      activeThread = 0;
    }
  }
}
activeThread = getCurrentThread();
uLock.unlock();
try {
  // do stuff here.
}
catch (const std::exception&) {
}
uLock.lock();
activeThread = 0;

在有人问我之前,我无法保证控制线程的创建时间,地点或方式。调用函数的线程可以来自任何地方。

0 个答案:

没有答案