如何为c中的pthread赋予执行顺序?

问题描述 投票:0回答:1

有三个pthread。

而且我想添加一个设置线程顺序的线程。

在我的源代码中,我得到随机结果。

ex)

1221个1个333

但是我想要1个1个1个222333

如何使用附加的pthread?

感谢阅读。

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

void *runner1(void *argument) {
    for (int i = 0; i < 3; i++) {
        printf("1 ");
    }
    return NULL;
}

void *runner2(void *argument) {
    for (int i = 0; i < 3; i++) {
        printf("2 ");
    }
    return NULL;
}

void *runner3(void *argument) {
    for (int i = 0; i < 3; i++) {
        printf("3 ");
    }
    return NULL;
}

int main() {
    pthread_t t1;
    pthread_t t2;
    pthread_t t3;

    pthread_create(&t1, NULL, runner1, NULL);
    pthread_create(&t2, NULL, runner2, NULL);
    pthread_create(&t3, NULL, runner3, NULL);

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);

    return 0;
}
c multithreading pthreads
1个回答
0
投票

我正在制作CPU调度模拟器

我不是真正的OS专家,但我不明白为什么actual调度程序需要多线程。 (至少不是一个简单的方法。)

典型调度程序的主要活动是将表示用户模式线程的对象从一个队列移动到另一个队列,以响应事件。大多数队列中的线程正在waiting进行处理。例如,每个互斥锁都有一个关联的队列,该队列包含所有等待“拥有”该互斥锁的线程。当某个线程释放互斥锁时,调度程序会从该互斥锁的队列中选择一个等待线程,并将该线程移至“运行队列”(即等待CPU运行的线程的容器)。当心跳计时器计时到时,调度程序可能会选择正在某个CPU上运行的线程,将其移至运行队列,然后从运行队列中选择其他线程以移至CPU。

调度程序本身不需要在any线程中运行。它只需要对事件做出反应。 (例如,调度程序的代码可以完全在中断服务例程中运行。)

[为了模拟这一点,我编写了一个带有单个“事件循环”的程序,该程序调用“事件处理程序”以响应发布的事件,其方式与硬件响应硬件中断而调用中断处理程序的方式相同。] >

© www.soinside.com 2019 - 2024. All rights reserved.