gpt4 book ai didi

c++ - pthread_yield 不能在线程之间正确循环

转载 作者:行者123 更新时间:2023-11-30 03:14:15 29 4
gpt4 key购买 nike

我有三个函数 A、B、C,我想将它们用于线程。我想运行它们进行一定数量的迭代,并希望在每次迭代时在它们之间切换。我在使用 pthread_yield() 时对它们的执行顺序有疑问

下面是这些函数的代码

void *A(void *arg){
int i = 0;
for (i=0; i < 3; i++){
printf("Hello A%d\n", i);
pthread_yield();
}
}

void *B(void *arg){
int i = 0;
for(i=0; i < 3; i++){
printf("Hello B%d\n", i);
pthread_yield();
}
}

void *C(void *arg){
int i = 0;
for(i=0; i < 3; i++){
printf("Hello C%d\n", i);
pthread_yield();
}
}

这是我创建线程的主要函数的代码

int main(){

pthread_t threadId_1, threadId_2, threadId_3;

printf("Before Thread\n");
pthread_create(&threadId_1, NULL, A, NULL);
pthread_create(&threadId_2, NULL, B, NULL);
pthread_create(&threadId_3, NULL, C, NULL);
// This line is Equivalent to Sleep // pthread_join(threadId_1, NULL);
//pthread_join(threadId_2, NULL);
//pthread_join(threadId_3, NULL);
sleep(1);
printf("After Thread\n");

}

当我运行程序时,我得到以下输出:

Before Thread
Hello C0
Hello B0
Hello C1
Hello B1
Hello C2
Hello B2
Hello A0
Hello A1
Hello A2
After Thread

我想要的不是这个

Before Thread
Hello A0
Hello B0
Hello C0
Hello A1
Hello B1
Hello C1
Hello A2
Hello B2
Hello C2
After Thread

如果我不使用 pthread_yield,我最后创建的线程将首先完成,然后是倒数第二个,最先创建的线程将最后完成。为什么会这样?

另外,当我使用 pthread_yield 时,为什么程序会在最后创建的两个线程 B 和 C 之间交替执行,然后才执行完然后转到线程 A?

如何在线程 A、B、C 之间完美交替的情况下实现我想要的输出?

最佳答案

man pthread_yield :

causes the calling thread to relinquish the CPU. The thread is placed at the end of the run queue for its static priority and another thread is scheduled to run. If the calling thread is the only thread in the highest priority list at that time, it will continue to run.

换句话说,pthread_yield 不保证挂起线程。因此,它无法帮助对线程的执行进行排序或序列化。对于您的任务来说,这是一个错误的工具。


I have three functions A, B, C, which I want to use for threading. I want to run them for certain number of iterations and wants to switch between them at every iteration.

一种解决方案是让一个线程依次运行函数 A、B 和 C。

另一个解决方案可能是将线程固定到同一个 CPU 并分配实时 FIFO 优先级,以便 pthread_yield 切换到另一个 FIFO 实时线程等待在同一个 CPU 上运行。然而,在这种情况下,并行性丢失了,首先破坏了拥有多个线程的目的。

关于c++ - pthread_yield 不能在线程之间正确循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58007337/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com