我初始化它開始運行的std::thread
後(即調用功函數),或者它只是開始運行時我叫join()
這是在文檔有點不清楚。在調用join()之前,std :: thread是否運行?
1
A
回答
2
當你實例化它,它就會執行。
加入用於使當前線程將等到其他線程執行完畢。
一些示例代碼從http://en.cppreference.com/w/cpp/thread/thread/thread
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 1 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int n = 0;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}
Possible output:
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 2 executing
Thread 1 executing
Final value of n is 5
1
一旦std::tread
創建它是處於運行狀態,其中它可以執行指令。
沒有保證,將在任何給定時間間隔做任何事情,但它做一些事情的可能性會更接近100%作爲間隔變長。
通常情況下,設計生動活潑切實保證,當你起牀到十分之一秒的時間間隔,所有非等待的線程會表現出一定的活性。
相關問題
- 1. 檢查std :: thread是否仍在運行
- 2. 是否可以在一次調用中調用Thread start()和join()?
- 3. Mingw32中是否支持std :: thread?
- 4. 是否加入std :: thread flush內存?
- 5. C++在調用std :: unique_lock之前解鎖std :: mutex等待
- 6. 可以不調用Thread#join嗎?
- 7. 使用std :: thread與std :: mutex
- 8. Toast在調用方法之前運行
- 9. 在libcxx中實現的std :: thread :: join在哪裏
- 10. 爲什麼std :: thread函數是由右值運行的?
- 11. 在std :: thread中使用std :: move
- 12. `scoped_thread`用'的std :: thread`
- 13. 如何在Join()被調用之前停止線程返回
- 14. 如何在調用Process.GetProcessById之前檢查進程是否仍在運行?
- 15. 在調用.str()之前是否可以知道std :: wostringstream的長度?
- 16. 在整個腳本完成解析之前是否運行javascript函數調用?
- 17. 是否可以在調用Spring Framework控制器方法之前運行代碼?
- 18. 在執行之前調用的回調之前,在FirebaseAuthClient實例上調用方法是否安全?
- 19. XCode std :: thread C++
- 20. MinGW和std :: thread
- 21. 檢測方法是否在調用之前進行了修飾
- 22. 是否需要在調用html()之前執行unbind()或off()
- 23. 調整在onTestSuccess/onTestFailure之前運行@AfterMethod
- 24. 錯誤C2280:'std :: thread :: thread(const std :: thread&)':嘗試引用已刪除的函數
- 25. 分離的std :: thread在終止後是否需要刪除?
- 26. std :: thread在主線程上執行回調函數
- 27. 在運行一些Javascript之前檢查DIV是否存在
- 28. 使用std :: thread使用std :: map的意外行爲
- 29. 在調用qRegisterMetaType之前,我是否必須調用Q_DECLARE_METATYPE?
- 30. std :: thread :: join主塊無限期加入塊
它立即開始運行。對於一個新線程來說,等到其他線程想要加入它時,它纔會毫無意義。 –
線程在運行狀態下創建,所以線程將在join()調用之前執行。並期待你的下一個問題,也許,沒有選擇創建一個處於停止狀態的線程,雖然你可以使用'std :: mutex'或類似的東西來暫停線程。 –