在Windows中更改提升线程优先级

我试图改变线程的优先级,但即时通讯没有运气。 我从GetLastError函数得到一个错误的句柄错误(types6)。 我虽然native_handle()返回线程的句柄?

有人知道怎么做吗?

void baseThread::applyPriority(uint8 priority) { #ifdef WIN32 if (!m_pThread) return; BOOL res; HANDLE th = m_pThread->native_handle(); switch (priority) { case REALTIME : res = SetPriorityClass(th, REALTIME_PRIORITY_CLASS); break; case HIGH : res = SetPriorityClass(th, HIGH_PRIORITY_CLASS); break; case ABOVE_NORMAL : res = SetPriorityClass(th, ABOVE_NORMAL_PRIORITY_CLASS); break; case NORMAL : res = SetPriorityClass(th, NORMAL_PRIORITY_CLASS); break; case BELOW_NORMAL : res = SetPriorityClass(th, BELOW_NORMAL_PRIORITY_CLASS); break; case IDLE : res = SetPriorityClass(th, IDLE_PRIORITY_CLASS); break; } if (res == FALSE) { int err = GetLastError(); } #endif } 

编辑:最后的代码:

 void baseThread::applyPriority(uint8 priority) { #ifdef WIN32 if (!m_pThread) return; BOOL res; HANDLE th = m_pThread->native_handle(); switch (priority) { case REALTIME : res = SetThreadPriority(th, THREAD_PRIORITY_TIME_CRITICAL); break; case HIGH : res = SetThreadPriority(th, THREAD_PRIORITY_HIGHEST); break; case ABOVE_NORMAL : res = SetThreadPriority(th, THREAD_PRIORITY_ABOVE_NORMAL); break; case NORMAL : res = SetThreadPriority(th, THREAD_PRIORITY_NORMAL); break; case BELOW_NORMAL : res = SetThreadPriority(th, THREAD_PRIORITY_BELOW_NORMAL); break; case IDLE : res = SetThreadPriority(th, THREAD_PRIORITY_LOWEST); break; } #endif } 

使用SetThreadPriority函数来设置线程的优先级。 SetPriorityClass用于设置进程的优先级。 您还必须更改优先级值,有关详细信息,请参阅SetThreadPriority的文档。

SetPriorityClass函数将HANDLE作为第一个参数,传递一个指向HANDLE的指针。 将其更改为:

 res = SetPriorityClass(*th, REALTIME_PRIORITY_CLASS); 

或者相当的东西。 内核可以告诉你传入的指针值不是一个真正有效的线程句柄,因为我猜它维护着一个当前分配的线程句柄的内部列表。 指针显然不在该列表中。 编译器不能真正实现更好的类型安全性,因为HANDLE是一种不透明的类型 – 你只需要非常小心你传入的东西。

顺便说一下,另一位评论者Dani是正确的, SetPriorityClass并不用于设置线程的优先级,反正你要使用SetThreadPriority 。 但是,那么我的建议仍然会成立,你需要传递一个句柄,而不是指向这样的指针。