SFML community forums

Help => General => Topic started by: timrh on October 17, 2016, 12:43:26 am

Title: Drawing sprites from another thread
Post by: timrh on October 17, 2016, 12:43:26 am
Hello i'm new in SFML, I want to draw sprite from another thread so i created thread:

void DrawMap(RenderWindow * render_window)
{
        while (true)
        {
                for (int y = 0; y < 5; y++)
                {
                        for (int x = 0; x < 10; x++)
                        {
                                face_img.setTextureRect(IntRect(rand() % 3 * 32, 0, 32, 32));
                                face_img.setPosition(x * 64, y * 64);
                                render_window->draw(face_img);
                        }
                }
                Sleep(100);
        }
}

In main() i have created RenderWindow:

        RenderWindow render_window(VideoMode(640, 320), "Map Generator", Style::Close + Style::Titlebar);


And I started the thread:
        Thread thread(&DrawMap, &render_window);
        thread.launch();
But nothing was drawed, i have message: "Failed to activate window's context"
Please help, and sorry I'm sure that my error is stupid but I'm new here.
Thanks!
Title: Re: Drawing sprites from another thread
Post by: DarkRoku12 on October 17, 2016, 05:28:35 am
Two threads cannot be using the same openGL context at the *same* time.
See sf::Window::setActive (http://www.sfml-dev.org/documentation/2.4.0/classsf_1_1Window.php#a17ccf8ece0ce0bf2f1e6698bcfa29731)

Tips:
1) Remember to use threads ONLY if you REALLY needs them.
2) Remember to take a look about Synchronization and Parallel programming (https://www.justsoftwaresolutions.co.uk/threading/locks-mutexes-semaphores.html).
3) Implement what you are doing without threads first when it have no-bugs then implement threads, so when you face a bug its more probable that multithreading is causing the bug and not your base algorithm.