From 3a732133cbde9aead5830c3431c02d7b6645a944 Mon Sep 17 00:00:00 2001 From: Laurent Gomila Date: Tue, 13 Dec 2011 19:06:13 +0100 Subject: [PATCH] Changed the Unix implementation of sf::Sleep to a more robust one --- src/SFML/System/Unix/Platform.cpp | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/SFML/System/Unix/Platform.cpp b/src/SFML/System/Unix/Platform.cpp index ffd2edea5..275c0fde3 100644 --- a/src/SFML/System/Unix/Platform.cpp +++ b/src/SFML/System/Unix/Platform.cpp @@ -26,6 +26,7 @@ // Headers //////////////////////////////////////////////////////////// #include +#include #include #include @@ -47,7 +48,35 @@ Uint64 Platform::GetSystemTime() //////////////////////////////////////////////////////////// void Platform::Sleep(Uint32 time) { - usleep(time * 1000); + // usleep is not reliable enough (it might block the + // whole process instead of just the current thread) + // so we must use pthread_cond_timedwait instead + // this implementation is inspired from Qt + + // first get the current time + timeval tv; + gettimeofday(&tv, NULL); + + // construct the time limit (current time + time to wait) + timespec ti; + ti.tv_nsec = (tv.tv_usec + (time % 1000) * 1000) * 1000; + ti.tv_sec = tv.tv_sec + (time / 1000) + (ti.tv_nsec / 1000000000); + ti.tv_nsec %= 1000000000; + + // create a mutex and thread condition + pthread_mutex_t mutex; + pthread_mutex_init(&mutex, 0); + pthread_cond_t condition; + pthread_cond_init(&condition, 0); + + // wait... + pthread_mutex_lock(&mutex); + pthread_cond_timedwait(&condition, &mutex, &ti); + pthread_mutex_unlock(&mutex); + + // destroy the mutex and condition + pthread_cond_destroy(&condition); + pthread_mutex_destroy(&mutex); } } // namespace priv