2017-11-15 2 views
0

Java에서 수행 한 Conway의 Life of game 일을 다시하고 싶었지만 이번에는 ncurses와 C++을 사용했습니다. 분명히 볼 수있는 속도로 시뮬레이션을 실행할 수 있도록 시간 초과 이벤트가 필요합니다. C++에서 Java로 작성된 것보다 시간 초과 된 이벤트를 작성하는 것이 훨씬 더 힘듭니다. 나는 Java에서보다 C++에서 경험이 없습니다. 나는 이미 온라인에서 살펴 보았고, 내가 발견 한 것은 내가 가지고있는 코드로 이끌었다. 실행시 터미널에서 결과가 생성되지 않습니다. 정확히 내가 뭘 잘못하고 있니?C++ : 타이머에 의해 반복적으로 호출되는 이벤트 만들기

MAIN.CPP :

#include <iostream> 
#include <functional> 
#include <chrono> 
#include <future> 
#include <cstdio> 

using namespace std; 

class callBackTimer //no idea how this works, got it from Stack Overflow thread 
{ 

public: 
    callBackTimer() 
    :_execute(false) 
    {} 

    void start(int interval, std::function<void(void)> func) 
    { 
     _execute = true; 
     std::thread([=]() 
        { 
         while (_execute) 
         { 
          func(); 
          std::this_thread::sleep_for(
          std::chrono::milliseconds(interval)); 
         } 
        }).detach(); 
    } 

    void stop() 
    { 
     _execute = false; 
    } 

private: 
    bool _execute; 

}; 

void timerExec() 
{ 
    cout << "SNAFU" << endl; 
} 

int main(int argc, const char * argv[]) 
{ 
    callBackTimer timer; //declare the timer 
    std::function<void(void)> exec = timerExec; //declare a pointer to timerExec 
    timer.start(25, std::bind(exec)); //start the timer 

    return 0; 
} 
+0

main에서 돌아 오기 전에 일부 입출력 차단을 시도하십시오 (예 :'getch()'). –

+0

@BenVoigt 무슨 뜻이야, 설명해? –

+0

스레드에서'detach()'를 호출하기 때문에,'main()'은 스레드를 기다리고 기다리지 않고 스레드를 즉시 파괴합니다. 'main()'이 쓰레드가 끝나기를 기다리고 ('while' 루프를 빠져 나갈 조건을 추가하는)'join()'을 사용하십시오. – cantordust

답변

0

당신이,하고있는 보통 join()를 호출하여 수행되는 것을 완료 스레드를 기다릴 필요가있다. 이 같은 아마 뭔가 :

#include <iostream> 
#include <functional> 
#include <chrono> 
#include <future> 
#include <cstdio> 

using namespace std; 

class callBackTimer //no idea how this works, got it from Stack Overflow thread 
{ 

public: 
    callBackTimer() 
     :_execute(false) 
    {} 

    void setup(int interval, std::function<void(void)> func) 
    { 
     _execute = true; 
     thread = std::thread([=]() 
     { 
//   while (_execute) 
      for (int steps = 0; steps < 100; ++steps) 
      { 
       func(); 
       std::this_thread::sleep_for(std::chrono::milliseconds(interval)); 
      } 
     }); 
    } 

    void stop() 
    { 
     _execute = false; 
    } 

    void run() 
    { 
     thread.join(); 
    } 

private: 
    bool _execute; 
    std::thread thread; 

}; 

void timerExec() 
{ 
    cout << "SNAFU" << endl; 
} 

int main(int argc, const char * argv[]) 
{ 
    callBackTimer timer; //declare the timer 
    std::function<void(void)> exec = timerExec; //declare a pointer to timerExec 
    timer.setup(25, std::bind(exec)); //start the timer 
    timer.run(); 

    return 0; 
} 

detach() 호출은 OK,하지만 당신은 수동으로 스레드에 대한 main() 대기를해야한다. while 루프에서 벗어날 조건이 필요합니다. 그렇지 않으면 영원히 계속됩니다. 희망이 도움이됩니다!

+0

기꺼이 도와 드리겠습니다. 쓰레드 간의 통신을 위해서'std :: condition_variable'을 봐야한다. – cantordust

관련 문제