전에 유니티 엔진을 잠깐 들여다보는데, Invoke라는 함수가 참 마음에 들었었던 기억이 있다.
그리고 후에 asio를 알아보던 중, deadline_timer라는 클래스를 제공한다는 걸 알았는데,
이걸 이용하면 유니티의 Invoke를 흉내낼 수 있을 거 같단 생각이 들었다.
다음은 deadline_timer를 이용한 예제..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | #include <iostream> #include <boost/asio.hpp> using namespace boost; asio::io_service service; asio::io_service::work work(service); // io_service의 run이 종료되지 않게 해주는 개체 void invoke(long time, std::function<void()> task) { auto t = std::make_shared<asio::deadline_timer>(service); t->expires_from_now(posix_time::seconds(time)); // 시간 설정은 expires 류 함수를 통해서 한다. t->async_wait([t, task](const auto& error) { // 작업의 등록 if (!error) { task(); } }); } int main(int argc, const char* argv[]) { auto task = []{ std::cout << "Hello!" << std::endl; }; invoke(3, task); // 3초 후 실행 invoke(5, task); // 5초 후 실행 service.run(); return 0; } | cs |