Multithreading c++;11将基于pthread的代码更新为std::thread或boost::thread
我有下面的代码,我想更新为更可移植和更友好的c++11。但是,如何替换pthread调用一直困扰着我。我可以使用std::this_thread::get_id()来获取线程id,但无法判断该线程是否仍处于活动状态Multithreading c++;11将基于pthread的代码更新为std::thread或boost::thread,multithreading,c++11,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(activeTh
pthread_t activeThread = 0;
pthread_t getCurrentThread() {
return pthread_self();
}
bool isActiveThreadAlive() {
if(activeThread == 0) {
return false;
}
return pthread_kill(activeThread, 0) != ESRCH;
}
可能的std::线程版本
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::thread::id activeThread=std::thread::id();
std::thread::id getCurrentThread(){
返回std::this_thread::get_id();
}
bool isActiveThreadAlive(){
if(activeThread==std::thread::id()){
返回false;
}
返回pthread_kill(activeThread,0)!= .ESRCH;//<代码> ISTAcVIEWTHELLIVION/CODE>是一个混淆的命名函数。也许代码> KyActuvSerialFipeFivie/Cube >是一个更具描述性的名称。检查线程,你对内脏没有控制的气味。据我所知,C++标准没有定义自省特性。知道<代码>线程::ID<代码>什么也不告诉。关于线程的当前状态。还要注意,POSIX指定了pthread_kill()的用法
将结束的线程作为未定义的行为,因此即使原始代码也不是standard-confirmant。Jackie,IsActivetReadAlive不会终止线程它发送信号值零,该信号值不做注释,但函数仍会测试线程是否处于活动状态,因此返回值仍然有效。本质上,它只是测试线程是否处于活动状态Tsyvarev,我不确定内省与我的代码有什么关系。据我所知,内省类似于反射,与在编译时访问您不知道的对象/函数有关。我只是试图确定线程是否处于活动状态。
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;