2 * Wrappers around mutex/cond/thread functions
4 * Copyright Red Hat, Inc. 2009
7 * Marcelo Tosatti <mtosatti@redhat.com>
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
)
31 pthread_mutexattr_t mutexattr
;
33 pthread_mutexattr_init(&mutexattr
);
34 pthread_mutexattr_settype(&mutexattr
, PTHREAD_MUTEX_ERRORCHECK
);
35 err
= pthread_mutex_init(&mutex
->lock
, &mutexattr
);
36 pthread_mutexattr_destroy(&mutexattr
);
38 error_exit(err
, __func__
);
41 void qemu_mutex_destroy(QemuMutex
*mutex
)
45 err
= pthread_mutex_destroy(&mutex
->lock
);
47 error_exit(err
, __func__
);
50 void qemu_mutex_lock(QemuMutex
*mutex
)
54 err
= pthread_mutex_lock(&mutex
->lock
);
56 error_exit(err
, __func__
);
59 int qemu_mutex_trylock(QemuMutex
*mutex
)
61 return pthread_mutex_trylock(&mutex
->lock
);
64 void qemu_mutex_unlock(QemuMutex
*mutex
)
68 err
= pthread_mutex_unlock(&mutex
->lock
);
70 error_exit(err
, __func__
);
73 void qemu_cond_init(QemuCond
*cond
)
77 err
= pthread_cond_init(&cond
->cond
, NULL
);
79 error_exit(err
, __func__
);
82 void qemu_cond_destroy(QemuCond
*cond
)
86 err
= pthread_cond_destroy(&cond
->cond
);
88 error_exit(err
, __func__
);
91 void qemu_cond_signal(QemuCond
*cond
)
95 err
= pthread_cond_signal(&cond
->cond
);
97 error_exit(err
, __func__
);
100 void qemu_cond_broadcast(QemuCond
*cond
)
104 err
= pthread_cond_broadcast(&cond
->cond
);
106 error_exit(err
, __func__
);
109 void qemu_cond_wait(QemuCond
*cond
, QemuMutex
*mutex
)
113 err
= pthread_cond_wait(&cond
->cond
, &mutex
->lock
);
115 error_exit(err
, __func__
);
118 void qemu_thread_create(QemuThread
*thread
,
119 void *(*start_routine
)(void*),
122 sigset_t set
, oldset
;
126 err
= pthread_attr_init(&attr
);
128 error_exit(err
, __func__
);
130 if (mode
== QEMU_THREAD_DETACHED
) {
131 err
= pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
);
133 error_exit(err
, __func__
);
137 /* Leave signal handling to the iothread. */
139 pthread_sigmask(SIG_SETMASK
, &set
, &oldset
);
140 err
= pthread_create(&thread
->thread
, &attr
, start_routine
, arg
);
142 error_exit(err
, __func__
);
144 pthread_sigmask(SIG_SETMASK
, &oldset
, NULL
);
146 pthread_attr_destroy(&attr
);
149 void qemu_thread_get_self(QemuThread
*thread
)
151 thread
->thread
= pthread_self();
154 bool qemu_thread_is_self(QemuThread
*thread
)
156 return pthread_equal(pthread_self(), thread
->thread
);
159 void qemu_thread_exit(void *retval
)
161 pthread_exit(retval
);
164 void *qemu_thread_join(QemuThread
*thread
)
169 err
= pthread_join(thread
->thread
, &ret
);
171 error_exit(err
, __func__
);