我正在构建一个 macOS 项目,在其中使用 cpp 中的 pthread 创建线程。我使用 pthread_attr_set_qos_class_np 设置 QOS 类,然后使用 pthread_attr_get_qos_class_np 检查 QOS 类的值。这些调用成功,但未设置 QOS 类别。下面是我从 swift 代码中调用的 cpp 函数。
bool CppThread::CreateThread ()
{
pthread_t threadId;
pthread_attr_t attr;
qos_class_t qos_class;
int relative_priority;
int rc = pthread_attr_init(&attr);
if (rc) {
printf ("pthread_attr_init failed");
}
if (pthread_attr_set_qos_class_np (&attr, QOS_CLASS_BACKGROUND, 5)) {
printf ("pthread_attr_set_qos_class_np failed\n");
}
int retval = pthread_create(&threadId, &attr, threadFunction, NULL);
if (retval) {
std::cerr << "Error creating thread" << std::endl;
return false;
}
if (pthread_attr_get_qos_class_np (&attr, &qos_class, &relative_priority)) {
printf ("pthread_attr_get_qos_class_np failed\n");
}
printf ("QoS class: %d, Relative priority: %d\n", qos_class, relative_priority);
pthread_join(threadId, NULL); // Wait for thread to finish
std::cout << "Thread finished" << std::endl;
return true;
}
输出:
QoS 等级:0,相对优先级:0
线程完成
我尝试设置多个 QOS 值,但输出始终将 QOS 类别值显示为 0。为什么没有设置?
在我的主要功能中..
pthread_attr_t _array_attr_pthread;
pthread_attr_init(&_array_attr_pthread);
pthread_attr_setinheritsched(&_array_attr_pthread,PTHREAD_EXPLICIT_SCHED);
// set my qos_attr
pthread_attr_set_qos_class_np(&_array_attr_pthread,QOS_CLASS_USER_INITIATED,-2);
// pthread_create here
pthread_create(&_thread_block_arr,&_array_attr_pthread,(void* (*)(void*))&_compute_mul_thread,(void*)((float*)_dim_3_arr));
线程函数_compute_mul_thread(我有以下定义)
void _compute_mul_thread(float* _dps_pointer){
qos_class_t qos_stack_var {0};
int priority_stack_var {0};
std::cout << pthread_self() << " | thread id | " << pthread_get_qos_class_np(pthread_self(),&qos_stack_var,&priority_stack_var) << std::endl;
std::cout << " results ---> " << qos_stack_var << " ---- " << priority_stack_var << std::endl;
从标准输出 -> 它打印 qos_class == 25 (因为它是 QOS_CLASS_USER_INTERACTIVE)和优先级 = 负 2(相对优先级)