我是 C 新手,我試圖讓控制臺在 5000 毫秒后“5 秒后”列印。然后在新執行緒宣告后立即列印“insta log”。
但是這樣做會崩潰并出現以下錯誤:
“除錯錯誤!
[程式路徑]
abort() 已被呼叫
"
這是我的代碼:
#include <iostream>
#include <thread>
#include <Windows.h>
#include <ctime>
using namespace std;
void f() {
Sleep(5000);
cout << "after 5 seconds" << endl;
}
int main() {
cout << "starting" << endl;
// Pass f and its parameters to thread
// object constructor as
thread t(&f);
cout << "insta log" << endl;
}
我不確定為什么會這樣。我四處搜索,發現了一個“修復”,但它使我的代碼無法按預期運行。
這是“修復”
#include <iostream>
#include <thread>
#include <Windows.h>
#include <ctime>
using namespace std;
void f() {
Sleep(5000);
cout << "after 5 seconds" << endl;
}
int main() {
cout << "starting" << endl;
// Pass f and its parameters to thread
// object constructor as
thread t(&f);
t.join();
cout << "insta log" << endl; // doesn't print for 5 seconds
}
這將洗掉錯誤訊息,但會在 5 秒內產生主執行緒。這使我的代碼無法按預期作業。
在此先感謝,任何幫助表示贊賞!
uj5u.com熱心網友回復:
這將洗掉錯誤訊息。
是的。
但產生主執行緒 5 秒。
這不是正在發生的事情!主執行緒正在等待您的第二個執行緒t完成(與屈服略有不同)。
之前的問題是主執行緒正在退出應用程式(并且您不允許在主執行緒退出后運行其他執行緒(這是因為子執行緒發生的事情高度依賴于執行緒實作并且它們非常瘋狂) .
在 C 類中,如果當前執行緒離開作用域而子執行緒未完成,他們會嘗試通過生成解構式std::thread來補償上述行為。terminate()
這意味著您通常必須呼叫該join()方法來等待孩子退出。
所以你通常做的是 1:創建一個std::thread在后臺做一些作業的物件 2:當你在本地做一些作業時。然后當你完成時,3:你呼叫join()并等待子物件也完成(如果它已經完成,則什么都不做)。然后您可以退出范圍(并退出主范圍)。
這使我的代碼無法按預期作業。
int main()
{
// STUFF.
// Create your thread.
thread t(&f);
// Print any thing you want.
// i.e. do the work you want to do in main.
cout << "insta log" << endl;
// When you have finished.
// wait for the child to finish.
t.join();
} // now the std::thread::~thread check to make sure the
// child thread of execution is no longer running.
uj5u.com熱心網友回復:
如果您在該對話框中單擊了“重試”,您就會看到代碼死亡的原因。它就在這里
~thread() noexcept {
if (joinable()) {
_STD terminate();
}
}
在 std::thread 的 MSVC 實作中。代碼說破壞仍然可連接(即正在運行)的執行緒是非法的。我不知道這是否是 c 定義的行為,快速搜索沒有顯示。無論如何,當你join執行緒時,你會等到它可以銷毀它
uj5u.com熱心網友回復:
函式已經作為指標傳遞,使用thread t(f)而不是thread t(&f).
此外,由于您的main()持續時間不超過執行緒或呼叫 a t.join(),因此程式將在執行緒完成其代碼之前結束,因此這可能是崩潰的另一個原因。事實上,這可能是崩潰的原因。
如果您想"insta log"立即列印,請t.join()在結束時呼叫main()。t.join()將等待執行緒t結束后再繼續。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451618.html
標籤:C
下一篇:顯示星號代替數字
