2 acodem ACodeM 于 2016.05.05 13:43 提问

关于linux pthread 调度策略FIFO,抢占CPU的问题

Hi 各位
最近在学习pthread时有点儿疑问,两个thread1和thread2调度策略均为FIFO,优先级分别为10和30,thread1先创建出来,无限循环打印thread1。 3秒后,创建thread2,无限循环打印thread2.
我理解当thread2执行时,thread1就完全被抢占了,只有thread2被不停打印出来。但是结果却是thread1和thread2都会打印出来。
代码如下,麻烦各位大神帮忙解释一下,谢谢了

 #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sched.h>
pthread_t createSchedFifoThread(void* (*pThreadFunc)(void*), int priority)
{
        struct sched_param param;
        int policy;
        int ret;
        pthread_t id = 0;

        pthread_attr_t thread_attr;
        ret = pthread_attr_init(&thread_attr);
        if (0 != ret) {
                printf("Attribute creation failed");
                return id;
        }

        ret = pthread_attr_setschedpolicy(&thread_attr, SCHED_FIFO);
        if (0 != ret) {
                printf("pthread_attr_setschedpolicy failed");
                return id;
        }

        param.sched_priority = priority;

        ret = pthread_attr_setschedparam(&thread_attr, &param);
        if (0 != ret) {
                printf("Setting pthread_attr_setschedparam failed");
                return id;
        }

        ret = pthread_create(&id, &thread_attr, pThreadFunc, NULL);
        if (0 != ret) {
                printf("Thread creation failed");
                return id;
        }

        pthread_attr_destroy(&thread_attr);
        return id;
}

void* thread1(void *arg)
{
        while(1)
        {
                printf("thread1\n");
        }
}

void* thread2(void *arg)
{
        while(1)
        {
                printf("thread2\n");
        }
}

int main(void)
{
        pthread_t id;
        printf("create thread1\n");
        id = createSchedFifoThread(thread1, 10);
        sleep(3);
        printf("create thread2\n");
        id = createSchedFifoThread(thread2, 30);
        while(1)
        {
                sleep(1);
        }
        return 0;
}

1个回答

CSDNXIAOD
CSDNXIAOD   2016.05.05 13:52

浅谈pthread和Linux调度策略
浅谈pthread和Linux调度策略
linux进程调度之 FIFO 和 RR 调度策略
----------------------biu~biu~biu~~~在下问答机器人小D,这是我依靠自己的聪明才智给出的答案,如果不正确,你来咬我啊!

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!