Pthreads堆栈优先级

时间:2019-06-19 08:34:00

标签: c multithreading pthreads thread-priority

我对pthread优先级没什么问题,我已经设置了调度程序FIFO。我有2个线程,每个线程都有不同的优先级。在我按A或B的项目中,一个线程开始工作。没关系,但是当一个线程工作并再次推送B(priority15)然后再推送A(priority 20)时,我的假设是线程A在堆栈队列中的B之前跳到B,而在第一个线程之后,优先级为20的下一个线程A然后是线程B (15)。是问题FIFO还是其他东西? PS:我不想使用信号量,我只想通过优先级和调度程序来解决它。谢谢

#include <stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<unistd.h>
#include <time.h>
#include <sched.h>

sem_t mutex;

void* levelOnefunction(void *a)
{
    sem_wait(&mutex);
    int* b = (int *) a;
    printf("Thread! next main!\n");
    printf("sched prior:%d\n",*b);
    sleep(3);
    sem_post(&mutex);
    return 0;
}

int main()
{
    char s;
    pthread_t t;
    pthread_attr_t tattr;
    struct sched_param param;

    sem_init(&mutex,0,1);
    pthread_attr_init(&tattr);

    if(pthread_attr_setschedpolicy(&tattr,SCHED_FIFO)!=0)
        printf("ERROR FIFO!\n");
    //pthread_setschedparam(t,SCHED_FIFO,&param);

    if(pthread_attr_getschedparam(&tattr,&param)!=0)
        printf("ERROR attr get sheduler!\n");

    /* int k =pthread_attr_setinheritsched(&tattr,PTHREAD_EXPLICIT_SCHED);

    if (k!=0)
        printf("ERROR\n"); */

    printf("Initial priority is %d \n",param.sched_priority);

    int min = sched_get_priority_min(SCHED_FIFO);
    int max = sched_get_priority_max(SCHED_FIFO);

    printf("MIN - %d ---> MAX - %d\n",min,max);

    scanf("%c",&s);

    while (s != '\0') 
    {
        if(s=='a')
        {
            printf("a\n");
            param.sched_priority=20;
            if(pthread_attr_setschedparam(&tattr,&param)!=0)
            printf("ERROR attr_setschedul!\n");
            printf("update priority is:%d\n",param.sched_priority);
            if(pthread_create(&t,&tattr,levelOnefunction,(void *)&param.sched_priority)!=0)
                printf("ERROR thread1\n");

            pthread_join(t,NULL);
            printf("main finish!\n");
            printf("%c end\n\n",s);
        }
        else if(s=='b')
        {
            printf("b\n");
            param.sched_priority=15;
            if(pthread_attr_setschedparam(&tattr,&param)!=0)
            printf("ERROR attr_setschedul!\n");
            if(pthread_create(&t,&tattr,levelOnefunction,(void *)&param.sched_priority)!=0)
            printf("ERROR Thread 2 ");

            pthread_join(t,NULL);
            printf("main finish!\n");
            printf("%c end\n\n",s);
        }
        else if(s=='\n')
        {
        }
        else if (s!='a' && s!='b')
        {
            printf("bad key\n");
        }
        scanf("%c",&s);
    }             
    sem_destroy(&mutex);     
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您在创建每个子线程后立即在主线程中调用pthread_join()

这意味着您一次不会创建多个子线程-创建一个子线程后,主线程将在pthread_join()中阻塞,直到该子线程完成。只有 then 会再次调用scanf()并可能创建另一个子线程。

线程优先级不包括在内。