Linux应用程序开发笔记:SCHED_RR模式线程调度测试

测试代码: 

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>              
#include <pthread.h>
#include <semaphore.h>

static sem_t sem;
static sem_t lock;

static void *pthread_fun1(void *arg)
{
    int cnt = 0;

    sem_post(&lock);

    while(1)
    {
        printf("pthread_fun1\n");
        sem_wait(&sem);
        printf("sem wait\n");
        cnt++;
        if (cnt > 5) {
            exit(0);
        }
        sleep(0);
    }
}

static void *pthread_fun2(void *arg)
{
    sem_wait(&lock);
    while(1)
    {
        printf("pthread_fun2\n");
        sem_post(&sem);
        printf("sem post\n");
        sleep(0);
    }
}

int main(void)
{
    int ret;
    pthread_t pt1, pt2;
    pthread_attr_t pthread_pro;
    struct sched_param parm;

    sem_init(&sem, 0, 0);
    sem_init(&lock, 0, 0);

    ret = pthread_attr_init(&pthread_pro);
    if (ret != 0) {
        return ret;
    }

    ret = pthread_attr_setschedpolicy(&pthread_pro, SCHED_RR);
    if (ret != 0) {
        return ret;
    }

    ret = pthread_attr_setdetachstate(&pthread_pro, PTHREAD_CREATE_DETACHED);
    if (ret != 0) {
        return ret;
    }

    parm.sched_priority = sched_get_priority_max(SCHED_RR);

    ret = pthread_attr_setschedparam(&pthread_pro, &parm);
    if (ret != 0) {
        return ret;
    }

    ret = pthread_create(&pt1, &pthread_pro, pthread_fun1, NULL);
    if (ret != 0) {
        return ret;
    }

    ret = pthread_create(&pt2, &pthread_pro, pthread_fun2, NULL);
    if (ret != 0) {
        return ret;
    }

    while (1) {
        sleep(100);
    }

    return 0;
}

输出结果:

pthread_fun1
pthread_fun2
sem post
sem wait
pthread_fun2
sem post
pthread_fun1
sem wait
pthread_fun2
sem post
pthread_fun1
sem wait
pthread_fun2
sem post
pthread_fun1
sem wait
pthread_fun2
sem post
pthread_fun1
sem wait
pthread_fun2
sem post
pthread_fun1
sem wait
 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值