15 #ifndef T3_WIDGET_THREAD_H
16 #define T3_WIDGET_THREAD_H
31 #ifndef _T3_WIDGET_INTERNAL
32 #error This header file is for internal use _only_!!
35 #if __cplusplus >= 201103L
37 #include <condition_variable>
42 using mutex = std::mutex;
43 using thread = std::thread;
44 namespace this_thread = std::this_thread;
45 template <
typename T>
using unique_lock = std::unique_lock<T>;
46 using defer_lock_t = std::defer_lock_t;
47 using condition_variable = std::condition_variable;
48 using cv_status = std::cv_status;
49 using timeout_t = std::chrono::time_point<std::chrono::system_clock>;
50 inline timeout_t timeout_time(
int microseconds) {
51 return std::chrono::system_clock::now() + std::chrono::microseconds(microseconds);
64 thread(
void (*f)()) { pthread_create(&handle, NULL, wrap_function, reinterpret_cast<void *>(f)); }
65 void join() {
void *result; pthread_join(handle, &result); }
66 const thread &operator=(
const thread &other) { handle = other.handle;
return *
this; }
69 static void *wrap_function(
void *f) {
reinterpret_cast<void (*)()
>(f)();
return NULL; }
73 namespace this_thread {
74 inline void yield() { pthread_yield(); }
77 typedef struct timespec timeout_t;
78 inline timeout_t timeout_time(
int microseconds) {
79 struct timeval timeval;
80 struct timespec result;
82 gettimeofday(&timeval, NULL);
83 timeval.tv_sec += microseconds / 1000000;
84 timeval.tv_usec += microseconds % 1000000;
85 if (timeval.tv_usec > 1000000) {
87 timeval.tv_usec -= 1000000;
89 result.tv_sec = timeval.tv_sec;
90 result.tv_nsec = (long) timeval.tv_usec * 1000;
96 mutex() { pthread_mutex_init(&mtx, NULL); }
97 ~
mutex() { pthread_mutex_destroy(&mtx); }
99 void lock() { pthread_mutex_lock(&mtx); }
100 void unlock() { pthread_mutex_unlock(&mtx); }
112 unique_lock(T &m) : locked(
true), mtx(m) { mtx.lock(); }
115 void lock() { mtx.lock(); locked =
true; }
116 void unlock() { mtx.unlock(); locked =
false; }
135 void notify_one() { pthread_cond_signal(&cond); }
136 void notify_all() { pthread_cond_broadcast(&cond); }
143 return pthread_cond_timedwait(&cond, &lock.mtx.mtx, &timeout) == ETIMEDOUT ? cv_status::timeout : cv_status::no_timeout;