請幫助我解決有關以下代碼輸出的簡單問題。
我認為只有在呼叫 join() 或 detach() 函式時才會執行執行緒。
所以,我希望輸出只列印“暫停 2 秒,ID = 59306 ”,而不列印“暫停 1 秒,ID = 10218 ”,因為我認為只有執行緒 2會被執行,而執行緒 1不會被執行。但是我錯了。
實際上,輸出實際上列印了上述兩行,這意味著執行緒 1 和 2 都被執行。是真的嗎?
請您向我解釋一下代碼實際上是如何執行兩個執行緒的?
===========================
#include <iostream> // std::cout
#include <thread> // std::thread, std::this_thread::sleep_for
#include <chrono> // std::chrono::seconds
void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended , ID = " << std::this_thread::get_id() << std::endl;
}
int main()
{
std::cout << "Spawning 2 threads...\n";
std::thread t1 (pause_thread,1);
std::thread t2 (pause_thread,2);
std::cout << "Done spawning threads. Now waiting for them to join:\n";
//t1.join();
t2.join();
//t1.detach();
//t2.detach();
std::cout << "All threads joined!\n";
return 0;
}
實際輸出:
Spawning 2 threads...
Done spawning threads. Now waiting for them to join:
pause of 1 seconds ended , ID = 10218
pause of 2 seconds ended , ID = 59306
All threads joined!
====================
更新:
Thanks to all comments and answers from everyone.
Now, I understand my incorrect logic because I mistakenly thought that a thread were executed only when the join() or detach() function is called.
I realize that a thread is executed as soon as it is created without the need to call join() or detach().
join() : In the main() function, after we call join() on a thread, the main() function will be blocked until the thread completes. After the thread completes, the main() function will resume, and the output from the thread will be shown along with any remaining output from the main() function.
detach() : In the main() function, if we call detach() on a thread, then, both the main() function and thread can run concurrently, and they are not blocked by each other or do not depend on each other in any way. In this case, if the main() function finishes before the detached thread completes, then we can only see the output from the main() function and NOT from the detached thread. However, if the detached thread finishes before the main() function completes, then we can see the output from both the thread and the main() function.
uj5u.com熱心網友回復:
執行緒不是在.join()呼叫它們時開始執行,而是在構造它們時開始執行。
.join()用于阻止呼叫執行緒的執行,直到加入的執行緒完成執行。main()由于您觀察到的原因,通常需要在退出之前加入所有執行緒:
當main()到達return陳述句時,std::thread物件的范圍就離開了。如果此時在管理執行緒上既沒有呼叫也沒有呼叫.join(),的解構式將呼叫(默認情況下)中止整個程式的執行。.detach()std::threadstd::threadstd::terminate()
即使您分離執行緒而不是加入它們,當在執行緒完成輸出之前main()沒有通過呼叫和退出阻塞足夠長的時間時,也會出現問題。.join()退出后main(),靜態存盤持續時間物件被銷毀。一個這樣的物件是std::cout。當執行緒在等待后嘗試通過輸出時std::cout,它已經被銷毀并且程式具有未定義的行為。
另請注意,分離t1和加入t2也不安全,盡管等待時間似乎表明了這一點。何時確切地安排執行緒執行取決于作業系統。執行緒可能會t2在 之前完成t1,在這種情況下,上述問題再次出現,導致程式再次出現未定義的行為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/422769.html
標籤:
上一篇:為什么使用gevent.joinall()而不是pool.imap_unordered()來運行Greenlets?
下一篇:HBase存盤檔案存盤位置
