55#include < SDL2/SDL.h>
66#include < SDL2/SDL_timer.h>
77#include < iostream>
8+ #include < thread>
9+ #include < thread>
10+ #include < future>
11+
12+ void nextBoardThreaded (Board board, std::promise<Board> promise) {
13+ promise.set_value (nextBoard (board));
14+ }
815
916int main () {
1017 // Initialize SDL
@@ -24,12 +31,17 @@ int main() {
2431 SDL_TEXTUREACCESS_STATIC, width, height);
2532
2633 // Generate initial board
27- auto p1 = startProfiling ();
2834 auto board = boardForSdlWindow (window);
29- stopProfiling (p1, " Generated first board" );
3035
3136 bool running = true ;
37+ bool recreateBoard = false ;
3238 while (running) {
39+ auto loopTimer = startProfiling ();
40+
41+ std::promise<Board> nextBoardPromise;
42+ auto nextBoardFuture = nextBoardPromise.get_future ();
43+ std::thread nextBoardThread (nextBoardThreaded, board, std::move (nextBoardPromise));
44+
3345 while (SDL_PollEvent (&event)) {
3446 // Exit when told, or Escape is pressed
3547 if ((event.type == SDL_KEYDOWN && event.key .keysym .sym == SDLK_ESCAPE) ||
@@ -40,24 +52,28 @@ int main() {
4052 // Re-create board when Enter is pressed
4153 else if (event.type == SDL_KEYDOWN &&
4254 event.key .keysym .scancode == SDL_SCANCODE_RETURN) {
43-
44- free (get<0 >(board));
45- board = boardForSdlWindow (window);
46- int width, height;
47- SDL_GetWindowSize (window, &width, &height);
48- SDL_DestroyTexture (texture);
49- texture = SDL_CreateTexture (renderer, SDL_PIXELFORMAT_ARGB8888,
50- SDL_TEXTUREACCESS_STATIC, width, height);
55+ recreateBoard = true ;
5156 }
5257 }
5358
54- auto p2 = startProfiling ();
55- board = nextBoard (board);
56- stopProfiling (p2, " Calculated next board" );
57-
58- auto p3 = startProfiling ();
5959 renderBoardSdl (board, renderer, texture);
60- stopProfiling (p3, " Rendered next board" );
60+
61+ nextBoardThread.join ();
62+ board = nextBoardFuture.get ();
63+
64+ // Re-create board when computation is complete
65+ if (recreateBoard) {
66+ free (get<0 >(board));
67+ board = boardForSdlWindow (window);
68+ int width, height;
69+ SDL_GetWindowSize (window, &width, &height);
70+ SDL_DestroyTexture (texture);
71+ texture = SDL_CreateTexture (renderer, SDL_PIXELFORMAT_ARGB8888,
72+ SDL_TEXTUREACCESS_STATIC, width, height);
73+ recreateBoard = false ;
74+ }
75+
76+ stopProfiling (loopTimer, " Done loop" );
6177 }
6278
6379 free (get<0 >(board));
0 commit comments