2014-12-21 5 views
2

첫째, 저는 VS2008을 사용하고 있습니다 (C++ 11을 지원하지 않습니다). 나는 그것을 제어 할 수없는 다른 사람의 컴파일러에서 컴파일해야하기 때문에 업그레이드 할 수없고 기본 라이브러리 만 사용해야합니다.C++ : 몇 초 후에 함수를 어떻게 실행합니까?

초를 경과하지 않고 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 
... 

답변

2

이 예제는 매우 간단한 스케줄링 알고리즘을 사용하여 수행하는 방법을 보여줍니다. 추가 스레드를 생성 할 필요가 없습니다.

위에서 언급 한 바와 같이
#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; 
     } 
    } 
} 
+0

이 오류가 발생했습니다 오류 LNK2019 : 확인되지 않은 외부 기호 __imp__timeGetTime @ 0이 (가) _main 함수에서 참조되었습니다. u 헤더 파일을 놓쳤습니까? – Mark

+0

보고있는 것은 링커 오류입니다.timeGetTime()은 Windows 멀티미디어 라이브러리의 일부이므로 winmm.lib를 라이브러리 목록에 추가하여 해당 라이브러리 (Windows 2000부터 모든 Windows 버전에 표준으로 포함되어 있음)에 링크해야합니다. 프로그램. –

+1

또는 파일의 맨 위에 다음 행을 추가 할 수 있습니다. #pragma comment (lib, "winmm.lib") –

-3

:

#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); 
    } 
} 
+0

, 내가 VS2008를 사용하고 있는데 불행하게도, VS2008는 도서관에서 ''를 찾을 수 없습니다 – Mark

-3

당신은있어 스레드 (코드 오렌지의 대답, 아마 더 좋은 방법)를 만들거나 모든 것을 작성해야 할 것입니다.

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(); 
    } 
} 
+0

아니, 나는 ... 그 첫 번째 깨는처럼 모두를 작성하지 않을거야 프로그래밍의 법칙 ... lol – Mark

+0

무차별 대입이 일반적으로 어떤 문제에 대한 가난한 접근법이라는 사실을 감안하면, 당신이 제공 한 해결책은 그 문제에 상세한 행동을 생성하지 않는다. –

1

실제로 실행하려는 코드와 실행 방법에 따라 달라집니다. 이렇게하는 간단한 방법은 별도의 스레드를 만들고이 스레드에 Sleep()을 작성하는 것입니다. Visual Studio 2008에서 업그레이드 할 수 없으므로 (정확히 기억한다면 C++ 11을 지원하지 않습니다), 기본 Windows 스레드 또는 Boost.Thread와 같은 라이브러리 구현을 사용해야합니다. Windows 스레드 사용 방법을 찾으려면 MSDN documentation on _beginthreadex() function을 참조하십시오. Boost.Thread에 대한 간단한 자습서는 here으로 볼 수 있습니다.

1) 윈도우 스레드 : 두 번째 예에서

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 

:

// 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-> %d\n", Counter); 
    // Destroy the thread object. 
    CloseHandle(hThread); 
} 

2) Boost.Thread의는 I가 제공하는 링크에서 직접 촬영 모두의

빠른 예, , 일반 함수 포인터를 boost::thread 생성자 인수로 사용할 수도 있습니다. 또한, 포인터를 사용하여 다중 인수로 함수를 사용할 수 있습니다. 고급 Windows API의 스레드는 제공하지 않습니다.

+0

내 코드를받는 사람이 플랫폼에서 코드를 컴파일해야하기 때문에 부스트를 사용할 수 없기 때문에 부스트를 사용할 수 없습니다. 나는 첫 번째 것을 시도 할 것이다. – Mark

관련 문제