barfatchen
barfatchen

Reputation: 1698

strange behavior for pthread_getschedparam function

sched_setscheduler is for all threads or main thread?

I have asked a question about SCHED_RR in main thread and threads main create, then I try to test it by the following source code :

void *Thread1(void *arg)
{
    pthread_detach(pthread_self());
    pthread_attr_t attr;
    pthread_attr_init (&attr);
    int ix = -1 ;
    int s = pthread_attr_getinheritsched (&attr, &ix );
    printf("s=(%d)\n",s) ;
    if( ix == PTHREAD_INHERIT_SCHED )
        printf("1.............\n") ;
    if( ix == PTHREAD_EXPLICIT_SCHED )
        printf("2.............\n") ;

    pid_t tid = syscall(SYS_gettid);
    printf("tid=(%d) \n",tid);
    int policy = -1;
    struct sched_param sp ;
    printf("before pthread_getschedparam \n");
    s = pthread_getschedparam(tid,&policy,&sp) ;
    printf("after pthread_getschedparam \n");
    printf("s=(%d)\n",s) ;
    printf("policy=(%d) , sp.sched_priority=(%d)\n",policy,sp.sched_priority) ;
}

int main()
{
    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);

    while( 1 )
        sleep ( 5 ) ;
}

I can see "before pthread_getschedparam " and can not see "after pthread_getschedparam" , then I try to modify the source as the following :

Modify the source , remove

s = pthread_getschedparam(tid,&policy,&sp) ;

and then change it to

s = pthread_getschedparam(pthread_self(),&policy,&sp) ;

Then it works fine , I like to know why in pthread_getschedparam , pthread_self() work , syscall(SYS_gettid) won't .

Upvotes: 0

Views: 454

Answers (1)

Alejandro López
Alejandro López

Reputation: 144

pthread_self() returns a pthread_t (unsigned long int), while syscall(SYS_gettid) returns the SPID (int). They are not the same identifier.

So if you are calling pthread_* functions, you need to provide the pthread id retrieved with pthread_self().

You can print both identifiers from a thread and you'll see how different they are.

Upvotes: 3

Related Questions