Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Launching a rendering thread stops main code execution (Visual Studio 2022)  (Read 844 times)

0 Members and 1 Guest are viewing this topic.

lt_halle

  • Newbie
  • *
  • Posts: 1
    • View Profile
Hi all. I've been working on learning SFML and I'm running into a frustrating issue. I've heard that there can be problems with rendering and running main logic on a single thread, so I'm trying to use a separate render thread to handle drawing to the screen. Relevant snippet of my code:

void RenderThread(sf::RenderWindow* gameWindow) {
    Renderer gameRenderer = Renderer();
    g_renderer = &gameRenderer;
    g_renderer->Init(gameWindow);
    while (g_renderer->GetGameWindow()->isOpen()) {
        if (g_renderer->Ready()) {
            g_renderer->Draw();
        }
    }
}

void StartRenderThread(sf::RenderWindow* gameWindow) {
    Thread thread(&RenderThread, gameWindow);
    g_renderThread = &thread;
    thread.launch();
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    RenderWindow gameWindow = RenderWindow(VideoMode({ 1920, 1080 }), GAME_NAME);
    gameWindow.setActive(false);
    StartRenderThread(&gameWindow);

    Game game;
    game.GameInit();
    while (gameWindow.isOpen()) {
        game.Update();
        sf::Event event;
        while (gameWindow.pollEvent(event)) {
            switch (event.type) {
            case sf::Event::Closed: gameWindow.close(); break;
            }
        }
    }
   
    g_renderThread->wait();

    return EXIT_SUCCESS;
}
 

Code is being executed in Visual Studio 2022 with a windows application (hence WinMain). Upon running the program, the window is created successfully and draws a circle to the screen as a test if I bypass the "ready to draw" logic. However, setting a breakpoint anywhere below "StartRenderThread(&gameWindow)" in the main function will result in it never being hit, and stepping line by line through the debugger results in it unpausing after calling thread.launch() in StartRenderThread.

Any help on this would be appreciated. Thanks :)

EDIT:
I'm a dummy. I realized the memory for the thread was being scoped by putting it in a function. Removing StartRenderThread's code into the main function fixed it.
« Last Edit: October 08, 2022, 12:21:25 am by lt_halle »

 

anything