pthread_getschedparam 函数的奇怪行为

strange behavior for pthread_getschedparam function

我在主线程和线程主创建中问了一个关于 SCHED_RR 的问题, 然后我尝试通过以下源代码对其进行测试:

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 ) ;
}

我能看到 "before pthread_getschedparam " 而看不到 "after pthread_getschedparam" ,然后我尝试修改源如下:

修改来源,移除

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

然后改成

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

然后它工作正常,我想知道为什么 pthread_getschedparam, pthread_self() 工作,系统调用 (SYS_gettid) 不会。

pthread_self() returns a pthread_t (unsigned long int),而 syscall(SYS_gettid) returns SPID (int)。它们不是相同的标识符。

因此,如果您正在调用 pthread_* 函数,则需要提供使用 pthread_self() 检索到的 pthread id。

您可以从线程中打印这两个标识符,您会看到它们有多么不同。