C++ : 如何在几秒钟后执行函数

C++ : How do I execute a function after several seconds?

本文关键字:几秒 函数 执行 C++      更新时间:2023-10-16

首先,我使用的是VS2008(不支持C++11(。我无法升级,只需要使用本机库,因为它需要在我无法控制的其他人的编译器上编译。

我想在 5 秒后自动运行代码,而不必轮询经过了多少秒。

这是我不完整的代码

#include <windows.h>
#include <iostream>
void runMeAfterFiveSeconds(){
     cout<<"I'm activated!"<<endl;
}
void main(){
     while(1){
          cout<<"hello there!"<<endl;
          Sleep(2000);
     }
}

示例输出

hello there!
hello there! //after 2 seconds
hello there! //after 4 seconds
I'm activated! //after 5 seconds
hello there! //after 6 seconds
hello there! //after 8 seconds
hello there! //after 10 seconds
I'm activated! //after 10 seconds
...

此示例演示如何使用非常简单的调度算法执行此操作。 不需要生成其他线程。

#include <stdio.h>
#include <windows.h>
int main(int argc, char ** argv)
{
   DWORD now                      = timeGetTime();
   DWORD nextPrintHelloThereTime  = now;
   DWORD nextPrintImActivatedTime = now+5000;
   while(1)
   {
      now = timeGetTime();
      DWORD nextEventTime = (nextPrintHelloThereTime < nextPrintImActivatedTime) ? nextPrintHelloThereTime : nextPrintImActivatedTime;
      DWORD millisecondsToSleep = nextEventTime-now;
      Sleep(millisecondsToSleep);
      now = timeGetTime();
      if (now >= nextPrintHelloThereTime)
      {
         printf("hello there!n");
         nextPrintHelloThereTime += 2000;
      }
      if (now >= nextPrintImActivatedTime)
      {
         printf("I'm activated!n");
         nextPrintImActivatedTime += 5000;
      }
   }
}

这实际上取决于您要执行的代码以及您希望如何执行它。这样做的非常简单的方法是创建一个单独的线程并在其中Sleep()。因此,由于您无法从Visual Studio 2008升级(如果我没记错的话,它不支持C++11(,因此您必须使用本机Windows线程或某些库实现,如Boost.Thread。若要查找如何使用 Windows 线程,请参阅 MSDN 有关 _beginthreadex(( 函数的文档。关于Boost.Thread的简短教程可以在这里看到。

两者的快速示例,直接取自我提供的链接:

1( 窗口线程:

// crt_begthrdex.cpp
// compile with: /MT
#include <windows.h>
#include <stdio.h>
#include <process.h>
unsigned Counter; 
unsigned __stdcall SecondThreadFunc( void* pArguments )
{
    printf( "In second thread...n" );
    while ( Counter < 1000000 )
        Counter++;
    _endthreadex( 0 );
    return 0;
} 
int main()
{ 
    HANDLE hThread;
    unsigned threadID;
    printf( "Creating second thread...n" );
    // Create the second thread.
    hThread = (HANDLE)_beginthreadex( NULL, 0, &SecondThreadFunc, NULL, 0, &threadID );
    // Wait until second thread terminates. If you comment out the line
    // below, Counter will not be correct because the thread has not
    // terminated, and Counter most likely has not been incremented to
    // 1000000 yet.
    WaitForSingleObject( hThread, INFINITE );
    printf( "Counter should be 1000000; it is-> %dn", Counter );
    // Destroy the thread object.
    CloseHandle( hThread );
}

2( 提升线程:

struct callable
{
    void operator()();
};
boost::thread copies_are_safe()
{
    callable x;
    return boost::thread(x);
} // x is destroyed, but the newly-created thread has a copy, so this is OK

在第二个示例中,您也可以使用纯函数指针作为构造函数参数boost::thread。此外,您可以使用指针来运行具有多个参数的功能 - 豪华的Windows API的线程不提供。

您可能只需要创建一个这样的线程:

#include <windows.h>
#include <iostream>
#include <thread>
void runMeAfterFiveSeconds(){
     while(true){
          sleep(5000);
          cout<<"I'm activated!"<<endl;   
     }     
}
void main(){
     std::thread th(runMeAfterFiveSeconds);
     while(1){
          cout<<"hello there!"<<endl;
          Sleep(2000);
     }
}

你要么做一个线程(编码橙色的答案,可能是更好的方法(,要么把它全部写出来。

void runMeAfterFiveSeconds(){
     cout << "I'm activated!" <<endl;        
}
void main(){
     while(1){
          cout << "hello there!" << endl;
          Sleep(2000);
          cout << "hello there!" << endl;
          Sleep(3000);
          runMeAfterFiveSeconds();
          Sleep(1000);
          cout << "hello there!" << endl;
          Sleep(2000);
          cout << "hello there!" << endl;
          Sleep(2000);
          cout << "hello there!" << endl;
          runMeAfterFiveSeconds();
     }
}