Hello my friends been a very long time since I visited the site hope you are all doing well.
Anyway on point, I am making a class that manages my SFML windows for me, rather than having to keep going through all the basic riff raff each time I want to make a 2D program. One of the things I would like to implement ( With hopefully performance increases ) is the event queue of the window being multithreaded.
The SFML code to grab the next event in the queue is:
1 2 3 4 5
|
sf::Event event; // Create reuseable event object
while(window.pollEvent(event)) // Keep popping next event from queue till none left
{
// Do something with event - Was it a button press, mouse moved etc etc
}
|
To make this multithreaded, and make the class a bit more dynamic I've so far came up with this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
void HandleEvents()
{
static size_t thread_count = 0; // Purely for debugging purposes
sf::Event event;
while(window.pollEvent(event))
{
std::thread t(&ManagedWindow::EventHandler,this,event); // Create thread
t.detach(); // Detach thread (S.O stated detach will clean up after itself upon process completion)
std::cout << "\rCreated event thread " << ++thread_count << ".";
}
}
virtual void EventHandler(sf::Event e) // I've made this a copy of event, something tells me the event may change while OS is creating thread (Probably not) but to be safe
{
switch(e.type)
{
case sf::Event::Closed: this->window.close(); break;
default: return;
}
return;
}
|
So far the code compiles and runs fine, until I get A LOT of events to happen. I slam on the keyboard and click rapidly, move the mouse etc. After enough key bashing program freezes and Windows wants you to force close it with error code 0xC0000005 which I googled to be an access violation.
The thread_count differs each freeze, could be 200 could be 10,000. The only time it does crash is when you mass spam events.
Is this down to how I am using threads? Is it bad practice to give each event it's own thread of execution? Should I give the EventHandler it's own thread, rather than the individual events?
Should I not try to multithread these events at all?
Thanks in advance for any help on multithreading practices. If you need the full source just say, but I'm prety sure it's down to the threading.