我正在尝试在 OSX 上实现类似于
pthread_tryjoin_np
的东西。
为此,我需要一种可靠的方法来查找 pthreat_t 是否已终止。
我找到了 mach_port API,我想知道是否可以将 thread_info() 用于此用例。 https://www.gnu.org/software/hurd/gnumach-doc/Thread-Information.html
#include <mach/mach_init.h>
#include <mach/thread_act.h>
#include <mach/mach_port.h>
bool info_available(mach_port_t thread)
{
mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT;
thread_basic_info_data_t info;
kern_return_t kr = thread_info(thread, THREAD_BASIC_INFO, (thread_info_t) &info, &count);
if (kr == KERN_SUCCESS && (info.flags & TH_FLAGS_IDLE) == 0) {
std::cout << "thread runnable state: " << info.run_state << std::endl;
return true;
}
else
{
std::cout << "invalid call to display info, thread might not be available: " << kr << std::endl;
return false;
}
}
void* thread_info_func(void *parameters)
{
info_available(mach_thread_self());
sleep(8);
pthread_exit(NULL);
}
int main()
{
pthread_t thread;
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
int create_result = pthread_create(&thread, &thread_attr, thread_info_func, NULL);
mach_port_t test_port = pthread_mach_thread_np(thread);
// works display running 1 or waiting 3
info_available(test_port);
pthread_join(m_thread, NULL);
// return 0, is is standard ? Is it reliable ?
mach_port_t test_port = pthread_mach_thread_np(thread);
// bool thread_terminated = test_port == 0;
// doesn't work, kr == KERN_INVALID_ARGUMENT
info_available(test_port);
// reliable ?
// thread_terminated = !info_available();
}
如果线程已终止,thread_info()
应该返回 TH_STATE_HALTED,但我认为如果线程不再存在,它会失败。在我的例子中,thread_info 退出时显示 KERN_INVALID_ARGUMENT。这是否意味着该线程不再存在?
顺便说一句,
pthread_mach_thread_np(thread)
返回0是否也意味着线程已终止?
pthread_getschedparam
的函数,它接受 pthread_t
作为参数,如果传入的线程 ID 不代表正在运行的线程,则返回错误 (ESRCH
)。
您仍然面临这样的风险:您感兴趣的线程已结束,并且启动了一个新线程,该新线程最终具有相同的线程 ID。我不知道它们的回收速度有多快,因此您必须进行一些测试才能了解这实际上在实践中存在多大问题。