sched_setscheduler is for all threads or main thread?

好久不见. 提交于 2019-12-10 10:13:43

问题


I have the following source which like to have SCHED_RR priority 90 :

int main(int argc, char** argv)
{
    const char *sched_policy[] = {
    "SCHED_OTHER",
    "SCHED_FIFO",
    "SCHED_RR",
    "SCHED_BATCH"
    };
    struct sched_param sp = {
        .sched_priority = 90
    };
    pid_t pid = getpid();
    printf("pid=(%d)\n",pid);
    sched_setscheduler(pid, SCHED_RR, &sp);
    printf("Scheduler Policy is %s.\n", sched_policy[sched_getscheduler(pid)]);

    pthread_t tid ;
    pthread_create(&tid , NULL, Thread1 , (void*)(long)3);
    pthread_create(&tid , NULL, Thread2 , (void*)(long)3);
    pthread_create(&tid , NULL, Thread3 , (void*)(long)3);
    while(1)
        sleep(100);
}

while shell "top" , I can see that process has PR with -91 , look like it works, As I know , in Linux , thread1 and thread2 and thread3 are different tasks from the main thread , they just share the same virtual memory , I like to know in this test , should I need to add

pthread_setschedparam(pthread_self(), SCHED_RR, &sp);

for all thread1,thread2 and thread3 so that all these 3 can be scheduled with SCHED_RR ?! or I don't need to do that ?! and how can I observe that thread1,thread2 and thread3 thread are SCHED_RR or SCHED_OTHER ?!

Edit :

sudo chrt -v -r 90 ./xxx.exe 

will see :

pid 7187's new scheduling policy: SCHED_RR
pid 7187's new scheduling priority: 90

how can I be sure this is only for main thread ?! or all threads in pid 7187 are SCHED_RR policy ?! and again , how to observe it ?!


回答1:


You shall check (and set, if required) the scheduler inheritance attributes before creating any new thread.

int pthread_attr_getinheritsched(const pthread_attr_t *attr, int *inheritsched);

int pthread_attr_setinheritsched(pthread_attr_t *attr, int inheritsched);

The pthread_attr_getinheritsched() will store in the variable pointed by inheritsched one of two possible values:

  • PTHREAD_INHERIT_SCHED - Threads that are created using attr
    inherit scheduling attributes from the creating thread; the scheduling attributes in attr are ignored.

  • PTHREAD_EXPLICIT_SCHED - Threads that are created using attr take their scheduling attributes from the values specified by the attributes object.

If you want that every newly created thread inherits the scheduler attributes of the calling task, you should set PTHREAD_INHERIT_SCHED (if not already set).

Also note:

The default setting of the inherit-scheduler attribute in a newly initialized thread attributes object is PTHREAD_INHERIT_SCHED

References

$ man pthread_setschedparam
$ man pthread_attr_setinheritsched
  • (Blockquoted material was copied from parts of release 3.74 of the Linux man-pages project.)


来源:https://stackoverflow.com/questions/38193214/sched-setscheduler-is-for-all-threads-or-main-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!