【问题标题】:Simulating round robin with pthreads使用 pthread 模拟循环
【发布时间】:2012-04-09 12:08:37
【问题描述】:

任务是同时存在 5 个线程,用户为每个线程分配一个突发时间。然后使用量子为 2 的循环算法来调度线程。例如,如果我用

运行程序
$ ./m 1 2 3 4 5

输出应该是

A 1
B 2
C 2
D 2
E 2
C 1
D 2
E 2
E 1

但现在我的输出只显示

A 1
B 2
C 2

由于程序出错,一个线程暂时没有结束,我觉得问题是这个线程不能解锁让下一个线程去抢锁。我的 sleep() 也不起作用。但我不知道如何修改我的代码以修复它们。我的代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
double times[5];
char process[] = {'A', 'B', 'C', 'D', 'E'};
int turn = 0;

void StartNext(int tid)     //choose the next thread to run
{
    int i;
    for(i = (tid + 1) % 5; times[i] == 0; i = (i + 1) % 5)
        if(i == tid)    //if every thread has finished
            return;
    turn = i;
}

void *Run(void *tid)    //the thread function
{
    int i = (int)tid;
    while(times[i] != 0)
    {
        while(turn != i);   //busy waiting till it is its turn
        if(times[i] > 2)
        {
            printf("%c 2\n", process[i]);
            sleep(2);   //sleep is to simulate the actual running time
            times[i] -= 2;
        }
        else if(times[i] > 0 && times[i] <= 2)      //this thread will have finished after this turn
        {
            printf("%c %lf\n", process[i], times[i]);
            sleep(times[i]);
            times[i] = 0;
        }
        StartNext(i);   //choose the next thread to run
    }
    pthread_exit(0);
}

int main(int argc, char **argv)
{
    pthread_t threads[5];
    int i, status;

    if(argc == 6)
    {
        for(i = 0; i < 5; i++)
            times[i] = atof(argv[i + 1]);   //input the burst time of each thread
        for(i = 0; i < 5; i++)
        {
            status = pthread_create(&threads[i], NULL, Run, (void *)i);    //Create threads
            if(status != 0)
            {
                printf("While creating thread %d, pthread_create returned error code %d\n", i, status);
                exit(-1);
            }
            pthread_join(threads[i], 0);    //Join threads
        }
    }
    return 0;
}

程序可以直接运行。谁能帮我弄清楚?谢谢!

【问题讨论】:

    标签: c operating-system pthreads scheduling


    【解决方案1】:

    我在阅读您的代码时发现了一些事情:

    1。在 Run 函数的开头,将 tid(指向 void 的指针)直接转换为 int。你不应该取消引用它吗?

    1. 最好将 int 设置为 volatile,这样编译器就不会对其值不发生变化做出任何假设。

    2. 当你第二次调用函数 sleep 时,你传递了一个 double (times[i]) 类型的参数,你应该传递一个 unsigned int 参数。像(unsigned int) times[i] 这样的直接演员应该可以解决这个问题。

    3. 您正在执行 pthread_join 创建其他线程。当您创建线程 3 并进入忙等待状态时,将不会创建其他线程。尝试将连接放在 for 块之后。

    【讨论】:

    • 谢谢。我真的不明白我应该如何根据你的第一点修改我的代码。而且它仍然没有解决问题...在我的示例中,是否实际创建了突发时间为“4”的线程?
    • 第一点你是对的,你将 int 直接嵌入到指针中,我没有看到。但是那里可能有问题,是的,创建线程时,我会编辑答案。
    • 谢谢!我应该意识到“加入”问题。现在它已修复,谢谢:) 最后一个问题:“加入”功能在这里真正做了什么?如果我删除了这一行,程序就不能运行,但是为什么呢?
    • 如果没有加入,你的主线程将在它创建其他线程后立即终止,从而杀死进程和新线程。所以连接只是为了防止主线程退出:)更多信息:computing.llnl.gov/tutorials/pthreads/#Joining
    • 嘿,如果它真的回答了你的问题,为什么不接受它呢? ;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多