我是c 初學者,所以不太懂
這是一個功能
void example(){
for(int i=0; i<5; i ){
// do stuff
}
}
如果我呼叫此函式,它將等待它完成后再繼續
int main(){
example();
otherThingsGoHere();
otherThingsGoHere();
otherThingsGoHere();
return 0;
}
otherThingsGoHere() 在 example() 完成之前不會被呼叫
我的目標是讓該功能能夠永遠回圈播放 60/70 fps
我確實讓它作業了,除了因為它處于無限回圈中,所以不會發生任何事情。
我作為 ac# 開發人員已經有一段時間了,我知道在 c# 中,您可以使用異步函式在單獨的執行緒上運行。我如何在 C 中實作這樣的東西?
編輯:我不是要求你把 otherThingsGoHere 放在 main 前面,因為其他東西將是另一個回圈,所以我需要它們同時運行
uj5u.com熱心網友回復:
您需要使用 a并從該新執行緒std::thread運行該函式。example()
Astd::thread可以在使用要運行的函式構造時啟動。它將可能與運行otherThingsGoHere. 我可能會寫,因為它取決于您的系統和內核數量。如果您有一臺具有多個內核的 PC,它實際上可以這樣運行。在main()退出之前,它應該等待另一個執行緒優雅地結束,通過呼叫thread::join().
您的案例的一個最小示例是:
#include <thread>
#include <iostream>
void example() {
for (int i = 0; i<5; i ) {
std::cout << "thread...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
void otherThingsGoHere() {
std::cout << "do other things ...\n";
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
int main() {
std::thread t{ example };
otherThingsGoHere();
otherThingsGoHere();
otherThingsGoHere();
t.join();
return 0;
}
更多資訊:C 中執行緒的簡單示例
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/467463.html
