I got a problem using a thread to handle window events, and drawing in
the main thread. I'm using SFML2 (rev 1562) on linux.
The following piece of code reproduce the problem.
It lead to something like a deadlock on my computer.
The x11 doc say:
The XInitThreads function initializes Xlib support for concurrent threads. This function must
be the first Xlib function a multi-threaded program calls, and it must complete before any other
Xlib call is made. This function returns a nonzero status if initialization was successful; other-
wise, it returns zero. On systems that do not support threads, this function always returns zero.
It is only necessary to call this function if multiple threads might use Xlib concurrently. If all
calls to Xlib functions are protected by some other access mechanism (for example, a mutual
exclusion lock in a toolkit or through explicit client programming), Xlib thread initialization is
not required. It is recommended that single-threaded programs not call this function.
Adding this call solve my problem, but it could be nice to handle it
inside SFML.
#include <iostream>
#include <SFML/Window.hpp>
#include <X11/Xlib.h>
class EventLoopThread : public sf::Thread
{
public:
EventLoopThread(sf::Window* w)
: win_(w)
{
}
private:
void Run()
{
sf::Event event;
while (true)
{
win_->WaitEvent(event);
}
}
sf::Window* win_;
};
int main()
{
//XInitThreads(); // Deadlock without this call
// Declare and create a new window
sf::Window window(sf::VideoMode(100, 100), "SFML window");
EventLoopThread th(&window);
th.Launch();
// Activate the window for OpenGL rendering
window.SetActive();
unsigned f = 0;
// The main loop - ends as soon as the window is closed
while (window.IsOpened())
{
// OpenGL drawing commands go here...
std::cout << f << " display start" << std::endl;
// End the current frame and display its contents on screen
window.Display();
std::cout << "display end" << std::endl;
f++;
}
}