关于设置Linux线程调度策略的实践

217 篇文章 29 订阅
156 篇文章 16 订阅

在Linux下运行应用方案,在某些场景下,为了调试和调优,可能会有调整任务的优先级的需求,它的基本流程是这样的:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>

static void * worker_thread1(void * param)
{
	while(1)
	{
		printf("%s line %d.\n", __func__, __LINE__);
		sleep(1);
	}
	return NULL;
}

static void * worker_thread(void * param)
{
	pthread_t demo_handle;

	int ret = pthread_create(&demo_handle, NULL, worker_thread1, NULL);
	if(ret != 0)
	{
		printf("%s line %d, fatal error.\n", __func__, __LINE__);
		return NULL;
	}

	while(1)
	{
		printf("%s line %d.\n", __func__, __LINE__);
		sleep(1);
	}
	pthread_join(demo_handle, NULL);
	return NULL;
}

int main(void)
{
	pthread_t pthread_demo_handle;
	int policy = 0;
	pthread_attr_t attr;
	struct sched_param param;

	bzero((void*)&param, sizeof(struct sched_param));
	pthread_attr_init(&attr);

	/*pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);*/
	//pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
	pthread_attr_setschedpolicy(&attr, SCHED_RR);
	pthread_attr_getschedpolicy(&attr, &policy);

	int max_priority = sched_get_priority_max(policy);
	int min_priority = sched_get_priority_min(policy);
	
	param.sched_priority = max_priority;

	pthread_attr_setschedparam(&attr, &param);
	pthread_attr_setstacksize(&attr, 1*1024*1024);

	int ret = pthread_create(&pthread_demo_handle, &attr, worker_thread, NULL);
	if(ret != 0)
	{
		printf("%s line %d, fatal error.\n", __func__, __LINE__);
		return -1;
	}

	pthread_join(pthread_demo_handle, NULL);
	return 0;
}

可是经过实际的测试,发现被创建任务的优先级并没有出现预期的结果

可以看到,根据sched节点获取到的信息,并未出现被修改线程的优先级成为实时优先级的情况,这是为何呢?

pthread_attr_setinheritsched

出现设置子线程调度策略不成功的原因是我们没有调用pthread_attr_setinheritsched并设置正确的参数。

pthread_attr_setinheritsched  的作用是设置线程是否继承父线程调度策略,分为两种情况:

  • attr:线程属性结构体地址
  • inheritsched:是否继承父线程的调度策略
  • PTHREAD_EXPLICIT_SCHED:不继承,只有不继承父线程的调度策略才可以设置线程的调度策略
  • PTHREAD_INHERIT_SCHED:继承父进程的调度策略 

 默认的情况下,设置的是PTHREAD_INHERIT_SCHED,也就是说,被创建线程完全按照父线程的调度策略创建,即便程序创建线程时,指定了不同的调度策略,这会导致设置失效,这就是我们上面遇到的情况。 

那该怎么处理呢?方法是调用

pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <stddef.h>
#include <stdint.h>
#include <unistd.h>
#include <pthread.h>

static void * worker_thread1(void * param)
{
	while(1)
	{
		printf("%s line %d.\n", __func__, __LINE__);
		sleep(1);
	}
	return NULL;
}

static void * worker_thread(void * param)
{
	pthread_t demo_handle;

	int ret = pthread_create(&demo_handle, NULL, worker_thread1, NULL);
	if(ret != 0)
	{
		printf("%s line %d, fatal error.\n", __func__, __LINE__);
		return NULL;
	}

	while(1)
	{
		printf("%s line %d.\n", __func__, __LINE__);
		sleep(1);
	}

	pthread_join(demo_handle, NULL);
	return NULL;
}

int main(void)
{
	pthread_t pthread_demo_handle;
	int policy = 0;
	pthread_attr_t attr;
	struct sched_param param;

	bzero((void*)&param, sizeof(struct sched_param));
	pthread_attr_init(&attr);

	pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
	//pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED);
	pthread_attr_setschedpolicy(&attr, SCHED_RR);
	pthread_attr_getschedpolicy(&attr, &policy);

	int max_priority = sched_get_priority_max(policy);
	int min_priority = sched_get_priority_min(policy);
	
	param.sched_priority = max_priority;

	pthread_attr_setschedparam(&attr, &param);
	pthread_attr_setstacksize(&attr, 1*1024*1024);

	int ret = pthread_create(&pthread_demo_handle, &attr, worker_thread, NULL);
	if(ret != 0)
	{
		printf("%s line %d, fatal error.\n", __func__, __LINE__);
		return -1;
	}

	pthread_join(pthread_demo_handle, NULL);
	return 0;
}

修改后的代码如下:

可见这次,新创建线程的调度策略和调度优先级都有了新的变化,变成了我们预期的设定值。

几个关键函数解析

bzero:

pthread_attr_init

int pthread_attr_setinheritsched(pthread_attr_t *a, int inherit):

pthread_attr_getinheritsched:

 pthread_attr_setschedpolicy:

 pthread_attr_getschedpolicy: 

sched_get_priority_max/sched_get_priority_min:

pthread_create:

运行过程中,改变线程调度策略和优先级的调用:pthread_setschedparam

关于调度策略的继承关系,可以从sched_fork函数下面的逻辑即可看出

p->policy的初始化是在struct task_struct分配的时候,由父线程的内容做memcpy完成的,所以一开始大部分的成员都是按照父线程的样子初始化的,后面在根据各种各样的条件,修改成子线程应该有的样子。

C++中运行时线程自身设置优先级:

#include <iostream>
#include <chrono>
#include<thread>
#include <pthread.h>
using namespace std;

int get_thread_info(void)
{
    pthread_t self = pthread_self();
    int policy;
    struct sched_param param;

    if (pthread_getschedparam(self, &policy, &param) != 0) {
        printf("%s line %d, pthread_getschedparam error.\n",
            __func__, __LINE__);
        return -1;
    }

    switch (policy) {
        case SCHED_FIFO:
            printf("SCHED_FIFO\n");
            break;
        case SCHED_RR:
            printf("SCHED_RR\n");
            break;
        case SCHED_OTHER:
            printf("SCHED_OTHER\n");
            break;
        default:
            printf("unknown.\n");
            break;
    }

    printf("current thread priority:%d\n", param.sched_priority);

    return 0;
}

void adjust_priority(void)
{
    struct sched_param params;

    params.sched_priority = 50;  // 50是优先级值,可以根据需求设置
    if(pthread_setschedparam(pthread_self(), SCHED_RR, &params) != 0) {
	    printf("%s line %d, error, failure.\n", __func__, __LINE__);
    } else {
	    printf("%s line %d, set priority success.\n", __func__, __LINE__);
    }

    get_thread_info();

    return;
}

int main(void)
{
	int nTimerValue = 100; //wait for 100 ms

	adjust_priority();
	for (int i = 0; /*i < 500*/; ++i) {
		auto start = std::chrono::steady_clock::now();
		std::this_thread::sleep_for(std::chrono::microseconds(nTimerValue));
		auto clock_end = std::chrono::steady_clock::now();
		long lElapsetimeMs = std::chrono::duration_cast<std::chrono::microseconds>(clock_end - start).count();
		char szBuff[255];
		sprintf(szBuff, "[%d] slept Time: %ld MiroSec\n", i, lElapsetimeMs);
		cout << szBuff;
	}

	cout << "system clock          : ";
	cout << chrono::system_clock::period::num << "/" << chrono::system_clock::period::den << "s" << endl;
	cout << "steady clock          : ";
	cout << chrono::steady_clock::period::num << "/" << chrono::steady_clock::period::den << "s" << endl;
	cout << "high resolution clock : ";
	cout << chrono::high_resolution_clock::period::num << "/" << chrono::high_resolution_clock::period::den << "s" << endl;

	system("pause");
	return 0;
}

UBUNTU22.04中的系统监视器,可以查看到普通进程(CFS)和高优先级进程(实时进程)


结束

  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

papaofdoudou

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值