C++で、スレッドの優先度を設定してみたのですが、思うようにスケジューリングされません。
優先度の設定方法がおかしいのか、実行環境の問題なのか、よくわかりません。
コードを以下に示します。
main()から生成するスレッドは2つ(th1、th2)です。
th1はsender()を、th2はrecver()を実行します。
th1の優先度はデフォルトで0です。
th2の優先度は、10に設定しています。
希望する動作は、th1がqueに"a"、"i"、"u"を詰めた後、th2がqueから"a"、"i"、"u"を取り出すというものです。
c++
1#include <iostream> 2#include <thread> 3#include <mutex> 4#include <queue> 5#include <string> 6 7std::mutex mtx; 8 9static std::queue<std::string> que; 10 11void sender() 12{ 13 std::this_thread::sleep_for(std::chrono::seconds(1)); 14 int policy; 15 struct sched_param sch; 16 int ret = pthread_getschedparam(pthread_self(), &policy, &sch); 17 std::cout << "sender " << sch.sched_priority << std::endl; 18 19 mtx.lock(); 20 que.push("a"); 21 que.push("i"); 22 que.push("u"); 23 mtx.unlock(); 24} 25 26void recver() 27{ 28 std::this_thread::sleep_for(std::chrono::seconds(1)); 29 int policy; 30 struct sched_param sch; 31 int ret = pthread_getschedparam(pthread_self(), &policy, &sch); 32 std::cout << "recver " << sch.sched_priority << std::endl; 33 34 mtx.lock(); 35 std::cout << que.front() << std::endl; que.pop(); 36 std::cout << que.front() << std::endl; que.pop(); 37 std::cout << que.front() << std::endl; que.pop(); 38 mtx.unlock(); 39} 40 41int main() 42{ 43 std::thread th1(sender); 44 std::thread th2(recver); 45 46 // 優先度 47 struct sched_param sch; 48 int policy; 49 pthread_getschedparam(th2.native_handle(), &policy, &sch); 50 sch.sched_priority = 10; 51 int ret = pthread_setschedparam(th2.native_handle(), SCHED_FIFO, &sch); 52 if(ret != 0) std::cout << "pthread_setschedparam error! " << ret << std::endl; 53 54 th1.join(); 55 th2.join(); 56 57 return 0; 58}
上記のコードを管理者権限で実行すると、th1とth2の優先度は設定されているようにみえるのですが、スケジューリングが思うようにできておらず、th2がth1よりも先に実行されたりします・・・。
SCHED_FIFOをSCHED_RRにしても変化はありませんでした。
ご存じの方がおられましたら、教えて頂けると幸いです。

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/17 14:48
2019/05/19 12:14
2019/11/05 09:08 編集
2019/11/09 22:18 編集