2 * Wrappers around mutex/cond/thread functions
4 * Copyright Red Hat, Inc. 2009
9 * This work is licensed under the terms of the GNU GPL, version 2 or later.
10 * See the COPYING file in the top-level directory.
20 #include "qemu-thread.h"
22 static void error_exit(int err, const char *msg)
24 fprintf(stderr, "qemu: %s: %s\n", msg, strerror(err));
28 void qemu_mutex_init(QemuMutex *mutex)
32 err = pthread_mutex_init(&mutex->lock, NULL);
34 error_exit(err, __func__);
37 void qemu_mutex_lock(QemuMutex *mutex)
41 err = pthread_mutex_lock(&mutex->lock);
43 error_exit(err, __func__);
46 int qemu_mutex_trylock(QemuMutex *mutex)
48 return pthread_mutex_trylock(&mutex->lock);
51 static void timespec_add_ms(struct timespec *ts, uint64_t msecs)
53 ts->tv_sec = ts->tv_sec + (long)(msecs / 1000);
54 ts->tv_nsec = (ts->tv_nsec + ((long)msecs % 1000) * 1000000);
55 if (ts->tv_nsec >= 1000000000) {
56 ts->tv_nsec -= 1000000000;
61 int qemu_mutex_timedlock(QemuMutex *mutex, uint64_t msecs)
66 clock_gettime(CLOCK_REALTIME, &ts);
67 timespec_add_ms(&ts, msecs);
69 err = pthread_mutex_timedlock(&mutex->lock, &ts);
70 if (err && err != ETIMEDOUT)
71 error_exit(err, __func__);
75 void qemu_mutex_unlock(QemuMutex *mutex)
79 err = pthread_mutex_unlock(&mutex->lock);
81 error_exit(err, __func__);
84 void qemu_cond_init(QemuCond *cond)
88 err = pthread_cond_init(&cond->cond, NULL);
90 error_exit(err, __func__);
93 void qemu_cond_signal(QemuCond *cond)
97 err = pthread_cond_signal(&cond->cond);
99 error_exit(err, __func__);
102 void qemu_cond_broadcast(QemuCond *cond)
106 err = pthread_cond_broadcast(&cond->cond);
108 error_exit(err, __func__);
111 void qemu_cond_wait(QemuCond *cond, QemuMutex *mutex)
115 err = pthread_cond_wait(&cond->cond, &mutex->lock);
117 error_exit(err, __func__);
120 int qemu_cond_timedwait(QemuCond *cond, QemuMutex *mutex, uint64_t msecs)
125 clock_gettime(CLOCK_REALTIME, &ts);
126 timespec_add_ms(&ts, msecs);
128 err = pthread_cond_timedwait(&cond->cond, &mutex->lock, &ts);
129 if (err && err != ETIMEDOUT)
130 error_exit(err, __func__);
134 void qemu_thread_create(QemuThread *thread,
135 void *(*start_routine)(void*),
140 err = pthread_create(&thread->thread, NULL, start_routine, arg);
142 error_exit(err, __func__);
145 void qemu_thread_signal(QemuThread *thread, int sig)
149 err = pthread_kill(thread->thread, sig);
151 error_exit(err, __func__);
154 void qemu_thread_self(QemuThread *thread)
156 thread->thread = pthread_self();
159 int qemu_thread_equal(QemuThread *thread1, QemuThread *thread2)
161 return (thread1->thread == thread2->thread);