SFML community forums

General => General discussions => Topic started by: uril on December 13, 2013, 06:27:04 pm

Title: How to use drawing in main thread and read from the keyboard in another thread
Post by: uril on December 13, 2013, 06:27:04 pm
Hi All,

I am trying to draw in main thread and read from the keyboard in another thread without success. I can draw but can not read number 5. Does anyone have any suggestions? Below my code:

#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>

using namespace std;

bool trigger = false;

void eventThread(sf::RenderWindow* window)
{
   sf::Event event;

while(trigger)
   {
      while (window->pollEvent(event))
               {
                // check the type of the event...
                       switch (event.type)
                       {
                         // key pressed
                         case sf::Event::KeyPressed:
                  if(event.key.code == sf::Keyboard::Num5) {
                           cout << "5" << endl;
                                          }
                  break;
                       } // end of switch
               } // end of Poll Event
   } // end of while of trigger
} // end of function


int main(int argc, char *argv[])
{

    // create the window
    sf::RenderWindow window(sf::VideoMode(1600, 900), "REG", sf::Style::Fullscreen);

    window.setActive(false);
    trigger = true;
    sf::Thread thread(&eventThread, &window);
    thread.launch();

    bool quit = false;
    while (!quit) {
            draw my staff with success
    }

   trigger = false;
   thread.wait();

   return 0;

}

Thank you,

Uril.
Title: Re: How to use drawing in main thread and read from the keyboard in another thread
Post by: G. on December 13, 2013, 06:46:11 pm
Quote from: http://www.sfml-dev.org/tutorials/2.1/window-window.php#things-to-know-about-windows
the event loop (more precisely, the pollEvent or waitEvent function) must be called in the same thread that created the window. This means that if you want to create a dedicated thread for event handling, you'll have to make sure that the window is created in this thread too.
It seems like you have to poll events in the same thread where the window was created.