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
 

猜你喜欢

转载自blog.csdn.net/u010018991/article/details/108098699