run_loop.h
1 /*
2 ** ClanLib SDK
3 ** Copyright (c) 1997-2016 The ClanLib Team
4 **
5 ** This software is provided 'as-is', without any express or implied
6 ** warranty. In no event will the authors be held liable for any damages
7 ** arising from the use of this software.
8 **
9 ** Permission is granted to anyone to use this software for any purpose,
10 ** including commercial applications, and to alter it and redistribute it
11 ** freely, subject to the following restrictions:
12 **
13 ** 1. The origin of this software must not be misrepresented; you must not
14 ** claim that you wrote the original software. If you use this software
15 ** in a product, an acknowledgment in the product documentation would be
16 ** appreciated but is not required.
17 ** 2. Altered source versions must be plainly marked as such, and must not be
18 ** misrepresented as being the original software.
19 ** 3. This notice may not be removed or altered from any source distribution.
20 **
21 ** Note: Some of the libraries ClanLib may link to may have additional
22 ** requirements or restrictions.
23 **
24 ** File Author(s):
25 **
26 ** Magnus Norddahl
27 */
28 
29 #pragma once
30 
31 #include <functional>
32 #include <future>
33 
34 namespace clan
35 {
37  class RunLoop
38  {
39  public:
41  static void run();
42 
44  static void exit();
45 
48  static bool process(int timeout_ms = 0);
49 
54  static void main_thread_async(std::function<void()> func);
55 
61  template<typename T>
62  static std::future<T> main_thread_task(std::function<T()> func)
63  {
64  auto promise = std::make_shared<std::promise<T>>();
65  main_thread_async([=]()
66  {
67  try
68  {
69  promise->set_value(func());
70  }
71  catch (...)
72  {
73  promise->set_exception(std::current_exception());
74  }
75  });
76  return promise->get_future();
77  }
78 
79  static std::future<void> main_thread_task(std::function<void()> func)
80  {
81  auto promise = std::make_shared<std::promise<void>>();
82  main_thread_async([=]()
83  {
84  try
85  {
86  func();
87  promise->set_value();
88  }
89  catch (...)
90  {
91  promise->set_exception(std::current_exception());
92  }
93  });
94  return promise->get_future();
95  }
96  };
97 }
Definition: clanapp.h:35
C style comment block.
static std::future< void > main_thread_task(std::function< void()> func)
Definition: run_loop.h:79
static void run()
Continously process messages until RunLoop::exit() is called.
static bool process(int timeout_ms=0)
Process messages for specified amount of time.
static std::future< T > main_thread_task(std::function< T()> func)
Executes a task on the main thread with a future result.
Definition: run_loop.h:62
Main thread message pump processing.
Definition: run_loop.h:37
static void exit()
Signal that message processing should end immediately.
static void main_thread_async(std::function< void()> func)
Executes a function on the main thread during message processing.