lundi 7 décembre 2015

c++11 update pthread based code to std::thread or boost::thread

I have the following code that I would like to update to be more portable and c++11 friendly. However, I'm stuck as how to replace the pthread calls. I can use std::this_thread::get_id() to get the thread id but can't tell if that thread is still alive.

  pthread_t activeThread = 0;

  pthread_t getCurrentThread() {
    return pthread_self();
  }

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

Potential std::thread version...

  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!!!
  }

What the code really needs to do is know if the thread has died from an exception or some other error that caused it to terminate without releasing the object. As in the following...

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;

And before anyone asks I do not have a guarantee of control over when, where or how the threads are created. The threads that call the functions may be from anywhere.

Aucun commentaire:

Enregistrer un commentaire