Linux 多線程編程
1、當沒有定義THREAD宏,定義JOIN
創建三個線程,每個線程都通過pthread_join(等待線程退出);運行結果:
首先,創建三個線程,主線程分別用pthread_join等待其退出,因為pthread_join是阻塞等待,從而也就有先後順序,從打印結果就可以看出;
2、當沒有定義THREAD宏,沒有定義JOIN
創建三個線程,後面加sleep;運行結果:
首先,創建三個線程,主線程沒有用pthread_join等待其退出;如果沒有加sleep,結果是:
因為創建了線程,根本沒有時間執行,為啥呢?(因為主線程(進程)執行完退出了,從而到處所有線程結束,沒有時間執行)。
所以主線程要sleep幾秒,讓你創建的線程有機會執行;而且你可以看到,沒有用pthread_join等待時,線程執行順序是不確定的。
你還可以發現,線程三的執行函數是一個while,這裏只打印了2句while裏的函數,因為用了pthread_cancel(取消線程);後面的sleep10所有的線程都退出了但是資源沒有釋放(占空間)為啥這樣說呢?看下面:
3、當定義了THREAD宏
這時,主線程是一個while 去創建線程
1)當線程執行函數中有pthread_detach(線程分離),此時線程資源自動釋放,結果:
2)當主線程用pthread_join(等待線程退出),此時結果:
比較1)和2),一個自動釋放資源不用主線程幹預,一個主線程join,然後釋放資源,而且可以看到join表現了阻塞和執行順序。
3)當線程執行函數沒有pthread_detach(線程分離)和主線程沒有pthread_join(等待線程結束),運行結果:
*為什麽會出現create error;因為創建的線程有一個最大數,為啥呢:
一個程序到一個進程,從磁盤到虛擬內存的映射,而虛擬內存是有限的,32位,4g;而且1g個內核用了,所以用戶只能使用3g,3g包含了代碼段,數據段,堆棧,malloc的空間等,所以空間是有限;而每創建一個線程,默認分配8M的堆棧,所以當你沒有釋放資源時,空間肯定不夠用,從而導致失敗。(不是創建所有線程都失敗,而是到那個最大值時出錯的而失敗的)
Linux 多線程編程