创建一个计时器以在X秒内调用函数 [英] Create a Timer to call a function in X Seconds

查看:91
本文介绍了创建一个计时器以在X秒内调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有要在5秒钟内执行的打印功能.问题是我想要函数中的其他所有内容.因此,例如,如果我的代码是:

So I have print function that I want to execute in 5 seconds. The Problem is that I want everything else in the function. So For example if my code is:

// insert code here...
printf("(5 seconds later) Hello"); /* should be executed in 5 seconds */
printf("heya");

例如在主要功能中.现在是棘手的部分.虽然第一行应在5秒钟内执行,但第二行应像正常情况一样执行(如果第一行根本不在那儿).因此输出为:

In the main function for example. Now here's the tricky part. While the first line should be executed in 5 seconds, the second line should be executed just like normal if the first line wasn't there at all. So the output would be:

heya
(5 seconds later) Hello

如果您熟悉Cocoa或Cocoa Touch,则这正是NSTimer类的工作方式.使用C ++,是否有比使用线程更简单或内置的方式?如果没有,我将如何使用多线程进行此操作?

If you familiar with Cocoa or Cocoa Touch, this is exactly how the NSTimer Class works. Using C++, is there a simpler or built in way other than using a thread? If not, how would I go about doing this using multi-threading?

推荐答案

使用< chrono> < thread> ,您可以创建一个非常简单的工具,但是简单的一个:

Using <chrono> and <thread>, you can create a pretty rudimentary, but easy one:

std::thread printLater{[] {
    std::this_thread::sleep_for(std::chrono::seconds(5));
    printf("(5 seconds later) Hello");
}};

printf("heya");

printLater.join(); //when you want to wait for the thread to complete

Pubby指出的另一种方法是使用 std :: async :

Another method, which Pubby points out, and has the advantage of automatically waiting for the thread to finish and not stopping if an exception is thrown, is to use std::async:

auto f = std::async(std::launch::async, [] {
    std::this_thread::sleep_for(std::chrono::seconds(5));
    printf("(5 seconds later) Hello");
});

printf("heya");

std :: async 的结果存储到变量中意味着该调用将启动一个新线程来运行该函数.如果不存储结果,则不会有新线程.这是该语言中的新陷阱之一.

The result of std::async being stored into a variable means the call will start a new thread to run the function in. If you don't store the result, no new thread. It's one of those new gotchas in the language.

请注意,它可能不是在打印五秒钟后才出现的,并且没有同步输出,因此您可能会得到交错的输出块( printf 是原子的,因此每个块的整个输出如果在每个线程中打印的内容不止一个,则调用将交错).如果没有同步,则不能保证哪个语句何时发生,因此如果您确实需要注意可能出现的同步问题,则应格外小心.不过,出于基本目的,这应该可行.

Note that it might not be precisely five seconds later when it prints, and there's no syncing of the output, so you might get interleaved output blocks (printf is atomic, so the entire output of each call would interleave) if printing more than just a single thing in each thread. Without synchronization, there's no guarantee of which statements happen when, so care should be taken if you do need to be aware of synchronization issues that can arise. For basic purposes, this should work, though.

这篇关于创建一个计时器以在X秒内调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆