Starvation in Priority Thread Schedule by Setting

2019-07-29 11:30发布

问题:

I'm trying to create some code that will simulate starvation of multiple threads based on priority scheduling (FIFO). The code below is supposed to set the program affinity to a single CPU so that no multi-threading can occur, then I spawn all the threads with different priorities and wait a sec to make sure they are all set up and in a waiting state after which I release the mutex and due to the FIFO scheduling policy the thread with the highest priority should be able to proceed and then run forever starving the other 2 threads. Here is my code...

#define _GNU_SOURCE
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <sched.h>
#include <unistd.h>

//global variables
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* tfun(void*n){
    struct sched_param param;
    int num_runs = 20;

    //set priority
    param.sched_priority = (int) n;
    sched_setscheduler(0, SCHED_FIFO, &param);

    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond, &mutex);
    pthread_mutex_unlock(&mutex);

    while(num_runs) {
            printf("thread priority: %d\n", (int) n);
            //num_runs = num_runs -1;
    }

    return NULL;
}

int main(int argc, char* argv[])       
{
    pthread_t tid1, tid2, tid3;
    cpu_set_t cpus;

    CPU_ZERO(&cpus);
    CPU_SET(0, &cpus);
    sched_setaffinity(0, sizeof(cpu_set_t), &cpus);

    pthread_create(&tid1, NULL, tfun, (void *) 40);
    pthread_create(&tid2, NULL, tfun, (void *) 30);
    pthread_create(&tid3, NULL, tfun, (void *) 20);

    sleep(1);
    pthread_mutex_lock(&mutex);
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mutex);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);

    return 0;
}

When I run it, instead of getting my expected behavior of "thread priority: 40" printed endlessly, it seems to cycle between all the different threads still and print them out as well.

I'm not sure if there is anything wrong with my code, but I am using the WSL (Windows subsystem for linux) and I was wondering if that was maybe causing my issue as the affinity setting is a linux thing that may not translate correctly in it?

build command
$gcc -o main main.c -pthread -std=gnu99 -D_GNU_SOURCE
run command (sudo because changing priorities)
$sudo ./main