-1

我是多线程的新手,正在关注“unix 环境中的高级编程”。我无法获得线程执行的顺序。我有以下代码。

int err1 = pthread_create(&first, NULL, disp, a);
int err2 = pthread_create(&second, NULL, disp, b);
int err3 = pthread_create(&third, NULL, disp, c);

但是与第三个 tid 相关的线程首先执行,然后是第二个,最后是第一个。不确定这是行为还是出了什么问题。

谢谢!拉胡尔。

4

3 回答 3

3

It's not deterministic. Threads run in parallel, so it will depend on how many processors and hyperthreading you have. If you want them in a given order, you need to use synchronisation points. Once started all threads run independently at their own rate.

于 2012-10-03T14:51:15.877 回答
2

There is no guarantee about the order of executing the code once they are created.
Only thing that can be guaranteed is that Thread 3 will be created after Thread 2 and Thread 2 will be created after Thread 1.
You cannot predict or assume that thread 2 will be spawned only after certain code has executed in thread 1. If you want to achieve something like that you need to provide your some Thread synchronization.

于 2012-10-03T14:51:25.473 回答
0

您的程序在一个线程中运行,并创建了另外三个。您可以保证的是其他三个线程的创建顺序以及它们将在某个阶段执行的顺序。操作系统可以停止您的主线程,并在创建新线程时按顺序为您完成新线程,它可以将它们粘在一些线程堆栈中,以便在您的主程序完成创建它们后稍后查看。关键是,你真的不知道。

如果你需要这三个线程按顺序执行并在下一个开始之前完成,你基本上需要首先不使用线程。

于 2012-10-03T15:13:37.740 回答