這是我如何做的基本模板,但經過四周搜索後,我發現旁邊沒有代碼示例,所以我猜測判斷是否最佳。
問題是,boost :: thread沒有一個構造函數,它允許在創建線程時傳遞pthead屬性,所以你必須在線程啓動後進行更改。我知道解決這個問題的唯一方法是通過進程/線程計劃繼承。除非另有指示,否則新線程將繼承其創建者的計劃/優先級,以便在創建工作線程之前更改當前線程,然後如果需要則更改回來。看起來很尷尬,但它是一種選擇。
下面是一個例子的破解,希望能夠解釋兩者。您可能需要根據需要更改策略和優先級,並以根用戶身份運行。
請注意您設置優先級的方式。各種限制適用。
#include <iostream>
#include <boost/thread/thread.hpp>
#include <unistd.h>
#include <sched.h>
#include <cstdio>
void* threadfunc()
{
sleep(5);
}
void displayAndChange(boost::thread& daThread)
{
int retcode;
int policy;
pthread_t threadID = (pthread_t) daThread.native_handle();
struct sched_param param;
if ((retcode = pthread_getschedparam(threadID, &policy, ¶m)) != 0)
{
errno = retcode;
perror("pthread_getschedparam");
exit(EXIT_FAILURE);
}
std::cout << "INHERITED: ";
std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" :
(policy == SCHED_RR) ? "SCHED_RR" :
(policy == SCHED_OTHER) ? "SCHED_OTHER" :
"???")
<< ", priority=" << param.sched_priority << std::endl;
policy = SCHED_FIFO;
param.sched_priority = 4;
if ((retcode = pthread_setschedparam(threadID, policy, ¶m)) != 0)
{
errno = retcode;
perror("pthread_setschedparam");
exit(EXIT_FAILURE);
}
std::cout << " CHANGED: ";
std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" :
(policy == SCHED_RR) ? "SCHED_RR" :
(policy == SCHED_OTHER) ? "SCHED_OTHER" :
"???")
<< ", priority=" << param.sched_priority << std::endl;
}
int main(int argc, char* argv[])
{
int policy, res;
struct sched_param param;
if ((policy = sched_getscheduler(getpid())) == -1)
{
perror("sched_getscheduler");
exit(EXIT_FAILURE);
}
if ((res = sched_getparam(getpid(), ¶m)) == -1)
{
perror("sched_getparam");
exit(EXIT_FAILURE);
}
std::cout << " ORIGINAL: ";
std::cout << "policy=" << ((policy == SCHED_FIFO) ? "SCHED_FIFO" :
(policy == SCHED_RR) ? "SCHED_RR" :
(policy == SCHED_OTHER) ? "SCHED_OTHER" :
"???")
<< ", priority=" << param.sched_priority << std::endl;
policy = SCHED_RR;
param.sched_priority = 2;
if ((res = sched_setscheduler(getpid(), policy, ¶m)) == -1)
{
perror("sched_setscheduler");
exit(EXIT_FAILURE);
}
boost::thread t1(&threadfunc);
displayAndChange(t1);
t1.join();
return 0;
}
Arafangion:你有什麼要支持的嗎? pthread_attr_setschedparam的linux手冊頁說它可以工作。此外,我個人的經驗是,它的工作原理與文件完全一致。 – 2011-11-18 07:10:46