pthread_attr_setinheritsched用于sched_setscheduler

时间:2016-08-12 02:09:46

标签: c++ multithreading scheduled-tasks thread-priority

我尝试测试一个将运行多个具有不同优先级的线程的应用程序,所以以下是我的测试ap,在linux x86_64中运行:

pthread_spinlock_t orderspinlock ;
int iGlbCnt=0 ;

void * donothing(void *arg)
{
    pthread_attr_t attr;
    pthread_attr_init (&attr);
    //int s = pthread_attr_setinheritsched (&attr, PTHREAD_INHERIT_SCHED );
    int s = pthread_attr_setinheritsched (&attr, PTHREAD_EXPLICIT_SCHED  );
    if( s != 0 ){
        printf("pthread_attr_setinheritsched error \n");
        exit(0) ;
    }

    int ipriority = (int)(long) arg ;
    const char *sched_policy[] = {
    "SCHED_OTHER",
    "SCHED_FIFO",
    "SCHED_RR",
    "SCHED_BATCH"
    };
    struct sched_param sp = {
        .sched_priority = ipriority
    };
    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_detach(pthread_self());
    int icnt=0;
    while(1){
        usleep( 1 ) ;
        pthread_spin_lock(&orderspinlock) ;
        iGlbCnt++ ;
        pthread_spin_unlock(&orderspinlock) ;
        if( ++icnt > 10000000 )
             break;
    }
    printf("thread done...(%d)\n",iGlbCnt);
}
int main(int argc, char **argv)
{
    pthread_spin_init(&orderspinlock, 0);

    pthread_attr_t attr;
    pthread_attr_init (&attr);
    //int s = pthread_attr_setinheritsched (&attr, PTHREAD_INHERIT_SCHED );
    int s = pthread_attr_setinheritsched (&attr, PTHREAD_EXPLICIT_SCHED  );
    if( s != 0 ){
        printf("pthread_attr_setinheritsched error \n");
        exit(0) ;
    }

    pthread_t tid;
    pthread_create(&tid, NULL, &donothing, (void *)(long) 80);
    pthread_create(&tid, NULL, &donothing, (void *)(long) 10);
    while( 1 )
        sleep( 5 ) ;
}

和g ++ --std = c ++ 11 y.cpp -pthread -o y.exe

运行:

sudo chrt -r -v 66 ./y.exe

另一个终端通过

观看线程
 top -H -p `pidof y.exe`

我看到线程PR都是-67,-67,-11,在两个线程都死了之后, 主线程PR = -11,我应该怎么做所有三个线程 优先级是-81,-11,-67,主线程保持在-67到最后?!

编辑:

int policy = 2 ;
s = pthread_setschedparam(pthread_self(),policy,&sp) ;

而不是:

pid_t pid = getpid();
sched_setscheduler(pid, SCHED_RR, &sp);

看起来对我很好。

0 个答案:

没有答案