OSX上实现类pthread_tryjoin_np:如何判断线程是否终止?
在 macOS 上实现类似 pthread_tryjoin_np 的功能:判断 pthread_t 是否终止
我想在 macOS 上实现类似 pthread_tryjoin_np 的功能,需要一种可靠的方法判断 pthread_t 是否已终止。我发现了 Mach Port API,想确认是否可以用 thread_info() 来实现这个需求。
代码示例
#include <mach/mach_init.h> #include <mach/thread_act.h> #include <mach/mach_port.h> #include <iostream> #include <unistd.h> #include <pthread.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); // 正常工作,输出运行状态1或等待状态3 info_available(test_port); pthread_join(thread, NULL); // 返回0,这是标准行为吗?是否可靠? mach_port_t test_port = pthread_mach_thread_np(thread); // bool thread_terminated = test_port == MACH_PORT_NULL; // 调用失败,kr == KERN_INVALID_ARGUMENT info_available(test_port); // 是否可靠? // thread_terminated = !info_available(); }
疑问点
- 按预期,
thread_info()在线程终止时应该返回TH_STATE_HALTED,但我测试时发现线程不存在时该函数调用失败,返回KERN_INVALID_ARGUMENT,这是否能判定线程已不存在? pthread_mach_thread_np(thread)返回 0 是否也表示线程已终止?这种判断方式可靠吗?
内容的提问来源于stack exchange,提问作者Paltoquet
相关产品推荐
相关产品推荐

