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

Author Topic: How to use drawing in main thread and read from the keyboard in another thread  (Read 1923 times)

0 Members and 1 Guest are viewing this topic.

uril

  • Newbie
  • *
  • Posts: 1
    • View Profile
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.

G.

  • Hero Member
  • *****
  • Posts: 1592
    • View Profile
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.