在C++中执行线程的奇怪顺序

All*_*lok 1 c c++ multithreading pthreads

我试图从Linux Tutorial Posix Threads执行第一个例子.这就是我的意思:

[alex@Allok c_c++]$ g++ -lpthread from.cpp
from.cpp: In function ‘int main()’:
from.cpp:10:22: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
from.cpp:11:22: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
[alex@Allok c_c++]$ ./a.out 
Thread 2 
Thread 1 
Thread 1 returns: 0
Thread 2 returns: 0
Run Code Online (Sandbox Code Playgroud)

问题是我希望输出像源一样说:

Thread 1
Thread 2
Thread 1 returns: 0
Thread 2 returns: 0
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会这样.谁能帮我?

[alex@Allok c_c++]$ uname -a
Linux Allok 3.3.2-1-ARCH #1 SMP PREEMPT Sat Apr 14 10:08:43 UTC 2012 i686 AMD Athlon(tm) II Neo K125 Processor AuthenticAMD GNU/Linux
Run Code Online (Sandbox Code Playgroud)

Oli*_*rth 8

根据定义,线程是异步执行的(它都是OS调度程序的奇思妙想).除非明确使用同步机制,否则您不能假设它们相对于彼此的执行方式.

  • 由于涉及大量的缓冲,在打印到标准输出时,事情变得更加疯狂. (2认同)