bob*_*obo 7 c++ function execution void-pointers
在javascript中有这个甜蜜,甜蜜的功能window.setTimeout( func, 1000 ) ;,它将在1000毫秒后异步调用func.
我想在C++中做类似的事情(没有多线程),所以我把一个示例循环放在一起,如:
#include <stdio.h>
struct Callback
{
// The _time_ this function will be executed.
double execTime ;
// The function to execute after execTime has passed
void* func ;
} ;
// Sample function to execute
void go()
{
puts( "GO" ) ;
}
// Global program-wide sense of time
double time ;
int main()
{
// start the timer
time = 0 ;
// Make a sample callback
Callback c1 ;
c1.execTime = 10000 ;
c1.func = go ;
while( 1 )
{
// its time to execute it
if( time > c1.execTime )
{
c1.func ; // !! doesn't work!
}
time++;
}
}
我怎样才能做出类似这样的工作?
在C++ 11问世之后,如果你使用的是c ++ 11支持的编译器,你可以使用lambda,variadic模板函数和异步线程来轻松地在c ++中模拟javascript函数.
这是我为setTimeOut编写的代码,它经过了全面测试:
setTimeOut功能的定义:
#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...);
});
};
Run Code Online (Sandbox Code Playgroud)
此函数通过使用c + 11的可变参数模板接受变量参数,代码可以向您展示如何使用它:
#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);
}
Run Code Online (Sandbox Code Playgroud)
制作Callback::func类型void (*)(),即
struct Callback
{
double execTime;
void (*func)();
};
Run Code Online (Sandbox Code Playgroud)
你可以这样调用函数:
c1.func();
Run Code Online (Sandbox Code Playgroud)
另外,不要忙碌等待.使用ualarmLinux或CreateWaitableTimerWindows上.