以下代碼foo每隔 5 秒列印一次傳遞給函式的引數。
function foo(arg) {
console.log(arg);
}
setInterval(() => foo(5), 5000);
我找到了這個答案:https ://stackoverflow.com/a/43373364/13798537 ,它以周期性間隔呼叫一個函式,但我不知道如何以周期性間隔呼叫一個函式,該函式接受引數,如javascript代碼所示.
是否有等效于 C 中的 javascript 代碼?
謝謝。
uj5u.com熱心網友回復:
您實際上可以非常接近 javascript 語法:
#include <iostream>
#include <chrono>
#include <thread>
#include <functional>
#include <memory>
#include <atomic>
using cancel_token_t = std::atomic_bool;
template<typename Fnc>
void set_interval(Fnc fun, std::chrono::steady_clock::duration interval,
std::shared_ptr<cancel_token_t> cancel_token=nullptr)
{
std::thread([fun=std::move(fun), interval, tok=std::move(cancel_token)]()
{
while (!tok || !*tok) // Call until token becomes true (if it is set)
{
auto next = std::chrono::steady_clock::now() interval;
fun();
std::this_thread::sleep_until(next);
}
}).detach();
}
void foo(int n)
{
std::cout << "Hello from foo("<<n<<")!\n";
}
int main()
{
using namespace std::chrono_literals;
auto cancel = std::make_shared<cancel_token_t>(false);
int x = 2;
// Ordinary rules for lambda capture apply so be careful
// about lifetime if captured by reference.
set_interval([x]{foo(5 x);}, 1000ms, cancel);
//set_interval([x]{foo(5 x);}, 1000ms); // Without token, runs until main exits.
std::this_thread::sleep_for(3s);
*cancel=true;
}
我已經修改了鏈接的問題并添加了一個取消標記,當設定為true. *cancel=true和回圈檢查之間當然有一些延遲。
我將令牌設為可選,如果不使用,執行緒將在從 main 回傳后行程退出時死亡。盡管 C 不保證這一點,但它可以在通用平臺上運行。
std::chrono強制正確使用時間單位。
隨意問我是否應該解釋什么。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/472986.html
上一篇:如何啟動多個結構
