Core/Thread: Rework ThreadImpl:Sleep for POSIX systems (fix yield behavior)
This commit is contained in:
parent
86fa6c5009
commit
6759abc878
|
|
@ -5,8 +5,9 @@
|
|||
#include <Nazara/Core/Posix/ThreadImpl.hpp>
|
||||
#include <Nazara/Core/Error.hpp>
|
||||
#include <Nazara/Core/Functor.hpp>
|
||||
#include <sched.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/time.h>
|
||||
#include <Nazara/Core/Debug.hpp>
|
||||
|
||||
namespace Nz
|
||||
|
|
@ -39,37 +40,20 @@ namespace Nz
|
|||
|
||||
void ThreadImpl::Sleep(UInt32 time)
|
||||
{
|
||||
// code from SFML2 Unix SleepImpl.cpp source https://github.com/LaurentGomila/SFML/blob/master/src/SFML/System/Unix/SleepImpl.cpp
|
||||
if (time == 0)
|
||||
sched_yield();
|
||||
else
|
||||
{
|
||||
struct timespec ts;
|
||||
ts.tv_sec = time / 1000;
|
||||
ts.tv_nsec = (time - ts.tv_sec * 1000) * 1'000'000;
|
||||
|
||||
// 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
|
||||
|
||||
// get the current time
|
||||
timeval tv;
|
||||
gettimeofday(&tv, nullptr);
|
||||
|
||||
// construct the time limit (current time + time to wait)
|
||||
timespec ti;
|
||||
ti.tv_nsec = (tv.tv_usec + (time % 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, nullptr);
|
||||
pthread_cond_t condition;
|
||||
pthread_cond_init(&condition, nullptr);
|
||||
|
||||
// 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);
|
||||
int r;
|
||||
do
|
||||
{
|
||||
r = nanosleep(&ts, &ts);
|
||||
}
|
||||
while (r == -1 && errno == EINTR);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue