Sau khi C++ 11 xuất hiện và nếu đang sử dụng trình biên dịch được hỗ trợ C++ 11, bạn có thể sử dụng lambda, Chức năng mẫu biến thể và chủ đề không đồng bộ để mô phỏng hàm javascript trong C++ dễ dàng.
Đây là mã tôi đã viết cho setTimeout, nó được kiểm tra đầy đủ: định nghĩa
setTimeout Chức năng của:
#include <windows.h>//different header file in linux
#include <future>
using namespace std;
template <typename... ParamTypes>
void setTimeOut(int milliseconds,std::function<void(ParamTypes...)> func,ParamTypes... parames)
{
std::async(std::launch::async,[=]()
{
Sleep(milliseconds);
func(parames...);
});
};
Chức năng này chấp nhận đối số biến bằng cách sử dụng c + mẫu variadic 11 của, Mã này có thể chỉ cho bạn cách sử dụng:
#include <iostream>
#include <thread>
#include <string>
#include <functional>
#include <windows.h>
#include <future>
using namespace std;
int main()
{
std::mutex locker;
std::function<void()> func1 = [&]()
{
std::unique_lock<std::mutex> lk(locker);
std::cout << "func 1 is trigged:" << " no parameter" << std::endl;
lk.unlock();
};
std::function<void(int)> func2 = [&](int param)
{
std::unique_lock<std::mutex> lk(locker);
std::cout << "func 2 is trigged:" << " int: " << param <<std::endl;
lk.unlock();
};
std::function<void(int,std::string)> func3 = [&](int param1,std::string param2)
{
std::unique_lock<std::mutex> lk(locker);
std::cout << "func 3 is trigged:" << " int: " << param1 << "; string: " << param2 << std::endl;
lk.unlock();
};
for(int index=0;index<100;index++)
{
std::unique_lock<std::mutex> lk1(locker);
std::cout << "set timer for func 1" << std::endl;
lk1.unlock();
setTimeOut<>(1000,func1);
std::unique_lock<std::mutex> lk2(locker);
std::cout << "set timer for func 2" << std::endl;
lk2.unlock();
setTimeOut<int>(2000,func2,10000);
std::unique_lock<std::mutex> lk3(locker);
std::cout << "set timer for func 3" << std::endl;
lk3.unlock();
setTimeOut<int,std::string>(5000,func3,10000,"ddddd");
}
Sleep(10000000);
}
Chế độ sleep() có hoạt động với nội dung bạn đang tìm không? –
Không thực sự.Tôi muốn chương trình tiếp tục chạy và gọi lại cho chúng sau – bobobobo
Bạn đang sử dụng nền tảng nào? – avakar