Get/Set Linux 中的 pthread 调度策略

Get/Set the pthread scheduling policy in Linux

下面的代码是我的操作系统课程中本书提供的示例。 编译时出现下面显示的错误。

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5

int main(int argc, char *argv[])
{
    int i, policy;
    pthread_t tid[NUM_THREADS];
    pthread_attr_t attr;

    pthread_attr_init(&attr);

    if(pthread_attr_getschedpolicy(&attr, &policy) != 0)
        fprintf(stderr, "Unable to get policy.\n");
    else{
        if(policy == SCHED_OTHER)
            printf("SCHED_OTHER\n");
        else if(policy == SCHED_RR)
            printf("SCHED_RR\n");
        else if(policy == SCHED_FIFO)
            printf("SCHED_FIFO\n");
    }

    if(pthread_attr_setschedpolicy(&attr, SCHED_FIFO) != 0)
        fprintf(stderr, "Unable to set policy.\n");
    /* create the threads */
    for(i = 0; i < NUM_THREADS; i++)
        pthread_create(&tid[i], &attr, runner, NULL);
    /* now join on each thread */
    for(i = 0; i < NUM_THREADS; i++)
        pthread_join(tid[i], NULL);
}

/* Each thread will begin control in this function */
void *runner(void *param)
{
    /* do some work... */

    pthread_exit(0);
}

我使用这个命令编译它...

gcc linux_scheduling.c -o scheduling

但是,我得到了这个错误。

linux_scheduling.c:32:34: error: 'runner' undeclared (first use in this function)   
pthread_create(&tid[i], &attr, runner, NULL);
                               ^
linux_scheduling.c:32:34: note: each undeclared identifier is report only once for each function it appears in

我尝试添加 -pthread:

gcc linux_scheduling.c -o scheduling -pthread

但错误依旧。

感谢您的帮助!

声明 runner 的原型,或者如果你不想声明,那么在 main 之前定义函数。这是因为 main 引用了函数并给了你这样的错误

你有正确的编译命令:

gcc linux_scheduling.c -o scheduling -pthread

但你需要输入:

void *runner(void *param);

main 开始之前声明它:

#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5

void *runner(void *param);

int main(int argc, char *argv[])
{
    ...