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