等同于C ++的window.setTimeout() [英] Equivalent to window.setTimeout() for C++
本文介绍了等同于C ++的window.setTimeout()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在javascript中有一个甜美的,甜蜜的函数 window.setTimeout(func,1000);
这将异步调用
我想在C ++中做类似的事情(没有多线程),所以我把一起一个示例循环,如:
#include< stdio.h>
struct回调
{
// _time_此函数将被执行。
double execTime;
// execTime之后执行的函数通过
void * func;
};
//执行示例函数
void go()
{
puts(GO);
}
//全局程序范围内的时间感觉
double time;
int main()
{
//启动计时器
time = 0;
//回调示例
Callback c1;
c1.execTime = 10000;
c1.func = go;
while(1)
{
//执行它的时间
if(时间> c1.execTime)
{
< b> c1.func; // !!不工作!
}
time ++;
}
}
如何做这样的工作?
c> c> c> c> code>,即
struct Callback
{
double execTime;
void(* func)();
};
您可以通过以下方式调用函数:
c1.func();
此外,请勿忙等待。使用 ualarm
在Linux上或 CreateWaitableTimer
。
In javascript there's this sweet, sweet function window.setTimeout( func, 1000 ) ;
which will asynchronously invoke func
after 1000 ms.
I want to do something similar in C++ (without multithreading), so I put together a sample loop like:
#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++; } }
How can I make something like this work?
解决方案
Make Callback::func
of type void (*)()
, i.e.
struct Callback
{
double execTime;
void (*func)();
};
You can call the function this way:
c1.func();
Also, don't busy-wait. Use ualarm
on Linux or CreateWaitableTimer
on Windows.
这篇关于等同于C ++的window.setTimeout()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文