SFML community forums

Help => General => Topic started by: lt_halle on October 08, 2022, 12:18:42 am

Title: Launching a rendering thread stops main code execution (Visual Studio 2022)
Post by: lt_halle on October 08, 2022, 12:18:42 am
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.