C++で、スレッドの優先度を設定してみたのですが、思うようにスケジューリングされません。
優先度の設定方法がおかしいのか、実行環境の問題なのか、よくわかりません。
コードを以下に示します。
main()から生成するスレッドは2つ(th1、th2)です。
th1はsender()を、th2はrecver()を実行します。
th1の優先度はデフォルトで0です。
th2の優先度は、10に設定しています。
希望する動作は、th1がqueに"a"、"i"、"u"を詰めた後、th2がqueから"a"、"i"、"u"を取り出すというものです。
c++
#include <iostream> #include <thread> #include <mutex> #include <queue> #include <string> std::mutex mtx; static std::queue<std::string> que; void sender() { std::this_thread::sleep_for(std::chrono::seconds(1)); int policy; struct sched_param sch; int ret = pthread_getschedparam(pthread_self(), &policy, &sch); std::cout << "sender " << sch.sched_priority << std::endl; mtx.lock(); que.push("a"); que.push("i"); que.push("u"); mtx.unlock(); } void recver() { std::this_thread::sleep_for(std::chrono::seconds(1)); int policy; struct sched_param sch; int ret = pthread_getschedparam(pthread_self(), &policy, &sch); std::cout << "recver " << sch.sched_priority << std::endl; mtx.lock(); std::cout << que.front() << std::endl; que.pop(); std::cout << que.front() << std::endl; que.pop(); std::cout << que.front() << std::endl; que.pop(); mtx.unlock(); } int main() { std::thread th1(sender); std::thread th2(recver); // 優先度 struct sched_param sch; int policy; pthread_getschedparam(th2.native_handle(), &policy, &sch); sch.sched_priority = 10; int ret = pthread_setschedparam(th2.native_handle(), SCHED_FIFO, &sch); if(ret != 0) std::cout << "pthread_setschedparam error! " << ret << std::endl; th1.join(); th2.join(); return 0; }
上記のコードを管理者権限で実行すると、th1とth2の優先度は設定されているようにみえるのですが、スケジューリングが思うようにできておらず、th2がth1よりも先に実行されたりします・・・。
SCHED_FIFOをSCHED_RRにしても変化はありませんでした。
ご存じの方がおられましたら、教えて頂けると幸いです。
まだ回答がついていません
会員登録して回答してみよう