1
我試着從Linux Tutorial Posix Threads執行第一個例子。 這就是我:在C++中執行線程的奇怪順序
[[email protected] 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]
[[email protected] c_c++]$ ./a.out
Thread 2
Thread 1
Thread 1 returns: 0
Thread 2 returns: 0
的問題是,我預計將有輸出,如源說:
Thread 1
Thread 2
Thread 1 returns: 0
Thread 2 returns: 0
我不明白爲什麼會發生。誰能幫我?
[[email protected] 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
爲什麼不呢?一旦你進行了並行處理,除非你採取措施使事情按照特定的順序進行,否則事情可能以他們想要的任何順序發生。 – 2012-04-28 14:17:44
「線程1」和「線程2」輸出不表示創建線程,而是表示線程函數中printf的操作。一旦創建了線程,就由操作系統來決定線程何時在處理器中獲得時間。 – veefu 2012-04-28 14:22:49