2 * Copyright (c) 2013 Nicira, Inc.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at:
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
18 #define OVS_THREAD_H 1
22 #include <sys/types.h>
23 #include "ovs-atomic.h"
26 /* glibc has some non-portable mutex types and initializers:
28 * - PTHREAD_MUTEX_ADAPTIVE_NP is a mutex type that works as a spinlock that
29 * falls back to a mutex after spinning for some number of iterations.
31 * - PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP is a non-portable initializer
32 * for an error-checking mutex.
34 * We use these definitions to fall back to PTHREAD_MUTEX_NORMAL instead in
37 * (glibc has other non-portable initializers, but we can't reasonably
38 * substitute for them here.) */
39 #ifdef PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
40 #define PTHREAD_MUTEX_ADAPTIVE PTHREAD_MUTEX_ADAPTIVE_NP
41 #define PTHREAD_ADAPTIVE_MUTEX_INITIALIZER \
42 PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP
44 #define PTHREAD_MUTEX_ADAPTIVE PTHREAD_MUTEX_NORMAL
45 #define PTHREAD_ADAPTIVE_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
48 #ifdef PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
49 #define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER \
50 PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP
52 #define PTHREAD_ERRORCHECK_MUTEX_INITIALIZER PTHREAD_MUTEX_INITIALIZER
55 /* Simple wrappers for pthreads functions. Most of these functions abort the
56 * process with an error message on any error. The *_trylock() functions are
57 * exceptions: they pass through a 0 or EBUSY return value to the caller and
58 * abort on any other error. */
59 void xpthread_mutex_init(pthread_mutex_t *, pthread_mutexattr_t *);
60 void xpthread_mutex_lock(pthread_mutex_t *mutex) OVS_ACQUIRES(mutex);
61 void xpthread_mutex_unlock(pthread_mutex_t *mutex) OVS_RELEASES(mutex);
62 int xpthread_mutex_trylock(pthread_mutex_t *);
64 void xpthread_rwlock_init(pthread_rwlock_t *, pthread_rwlockattr_t *);
65 void xpthread_rwlock_rdlock(pthread_rwlock_t *rwlock) OVS_ACQUIRES(rwlock);
66 void xpthread_rwlock_wrlock(pthread_rwlock_t *rwlock) OVS_ACQUIRES(rwlock);
67 void xpthread_rwlock_unlock(pthread_rwlock_t *rwlock) OVS_RELEASES(rwlock);
68 int xpthread_rwlock_tryrdlock(pthread_rwlock_t *);
69 int xpthread_rwlock_trywrlock(pthread_rwlock_t *);
71 void xpthread_cond_init(pthread_cond_t *, pthread_condattr_t *);
72 void xpthread_cond_signal(pthread_cond_t *);
73 void xpthread_cond_broadcast(pthread_cond_t *);
74 void xpthread_cond_wait(pthread_cond_t *, pthread_mutex_t *mutex)
78 /* Replace these functions by the macros already defined in the <pthread.h>
79 * annotations, because the macro definitions have correct semantics for the
80 * conditional acquisition that can't be captured in a function annotation.
81 * The difference in semantics from pthread_*() to xpthread_*() does not matter
82 * because sparse is not a compiler. */
83 #define xpthread_mutex_trylock pthread_mutex_trylock
84 #define xpthread_rwlock_tryrdlock pthread_rwlock_tryrdlock
85 #define xpthread_rwlock_trywrlock pthread_rwlock_trywrlock
88 void xpthread_key_create(pthread_key_t *, void (*destructor)(void *));
90 void xpthread_create(pthread_t *, pthread_attr_t *, void *(*)(void *), void *);
94 * Multiple forms of per-thread data exist, each with its own pluses and
97 * - POSIX per-thread data via pthread_key_t is portable to any pthreads
98 * implementation, and allows a destructor function to be defined. It
99 * only (directly) supports per-thread pointers, which are always
100 * initialized to NULL. It requires once-only allocation of a
101 * pthread_key_t value. It is relatively slow.
103 * - The thread_local feature newly defined in C11 <threads.h> works with
104 * any data type and initializer, and it is fast. thread_local does not
105 * require once-only initialization like pthread_key_t. C11 does not
106 * define what happens if one attempts to access a thread_local object
107 * from a thread other than the one to which that object belongs. There
108 * is no provision to call a user-specified destructor when a thread
111 * - The __thread keyword is a GCC extension similar to thread_local but
112 * with a longer history. __thread is not portable to every GCC version
113 * or environment. __thread does not restrict the use of a thread-local
114 * object outside its own thread.
116 * Here's a handy summary:
118 * pthread_key_t thread_local __thread
119 * ------------- ------------ -------------
120 * portability high low medium
121 * speed low high high
122 * supports destructors? yes no no
123 * needs key allocation? yes no no
124 * arbitrary initializer? no yes yes
125 * cross-thread access? yes no yes
128 /* DEFINE_PER_THREAD_DATA(TYPE, NAME, INITIALIZER).
130 * One should prefer to use POSIX per-thread data, via pthread_key_t, when its
131 * performance is acceptable, because of its portability (see the table above).
132 * This macro is an alternatives that takes advantage of thread_local (and
133 * __thread), for its performance, when it is available, and falls back to
134 * POSIX per-thread data otherwise.
136 * Defines per-thread variable NAME with the given TYPE, initialized to
137 * INITIALIZER (which must be valid as an initializer for a variable with
140 * The public interface to the variable is:
142 * TYPE *NAME_get(void)
143 * TYPE *NAME_get_unsafe(void)
145 * Returns the address of this thread's instance of NAME.
147 * Use NAME_get() in a context where this might be the first use of the
148 * per-thread variable in the program. Use NAME_get_unsafe(), which
149 * avoids a conditional test and is thus slightly faster, in a context
150 * where one knows that NAME_get() has already been called previously.
152 * There is no "NAME_set()" (or "NAME_set_unsafe()") function. To set the
153 * value of the per-thread variable, dereference the pointer returned by
154 * TYPE_get() or TYPE_get_unsafe(), e.g. *TYPE_get() = 0.
156 #if HAVE_THREAD_LOCAL || HAVE___THREAD
158 #if HAVE_THREAD_LOCAL
161 #define thread_local __thread
166 #define DEFINE_PER_THREAD_DATA(TYPE, NAME, ...) \
167 typedef TYPE NAME##_type; \
168 static thread_local NAME##_type NAME##_var = __VA_ARGS__; \
170 static NAME##_type * \
171 NAME##_get_unsafe(void) \
173 return &NAME##_var; \
176 static NAME##_type * \
179 return NAME##_get_unsafe(); \
181 #else /* no C implementation support for thread-local storage */
182 #define DEFINE_PER_THREAD_DATA(TYPE, NAME, ...) \
183 typedef TYPE NAME##_type; \
184 static pthread_key_t NAME##_key; \
186 static NAME##_type * \
187 NAME##_get_unsafe(void) \
189 return pthread_getspecific(NAME##_key); \
193 NAME##_once_init(void) \
195 if (pthread_key_create(&NAME##_key, free)) { \
200 static NAME##_type * \
203 static pthread_once_t once = PTHREAD_ONCE_INIT; \
204 NAME##_type *value; \
206 pthread_once(&once, NAME##_once_init); \
207 value = NAME##_get_unsafe(); \
209 static const NAME##_type initial_value = __VA_ARGS__; \
211 value = xmalloc(sizeof *value); \
212 *value = initial_value; \
213 pthread_setspecific(NAME##_key, value); \
219 /* DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME).
221 * This is a simple wrapper around POSIX per-thread data primitives. It
222 * defines per-thread variable NAME with the given TYPE, which must be a
223 * pointer type. In each thread, the per-thread variable is initialized to
224 * NULL. When a thread terminates, the variable is freed with free().
226 * The public interface to the variable is:
228 * TYPE NAME_get(void)
229 * TYPE NAME_get_unsafe(void)
231 * Returns the value of per-thread variable NAME in this thread.
233 * Use NAME_get() in a context where this might be the first use of the
234 * per-thread variable in the program. Use NAME_get_unsafe(), which
235 * avoids a conditional test and is thus slightly faster, in a context
236 * where one knows that NAME_get() has already been called previously.
238 * TYPE NAME_set(TYPE new_value)
239 * TYPE NAME_set_unsafe(TYPE new_value)
241 * Sets the value of per-thread variable NAME to 'new_value' in this
242 * thread, and returns its previous value.
244 * Use NAME_set() in a context where this might be the first use of the
245 * per-thread variable in the program. Use NAME_set_unsafe(), which
246 * avoids a conditional test and is thus slightly faster, in a context
247 * where one knows that NAME_set() has already been called previously.
249 #define DEFINE_PER_THREAD_MALLOCED_DATA(TYPE, NAME) \
250 static pthread_key_t NAME##_key; \
253 NAME##_once_init(void) \
255 if (pthread_key_create(&NAME##_key, free)) { \
263 static pthread_once_t once = PTHREAD_ONCE_INIT; \
264 pthread_once(&once, NAME##_once_init); \
268 NAME##_get_unsafe(void) \
270 return pthread_getspecific(NAME##_key); \
273 static OVS_UNUSED TYPE \
277 return NAME##_get_unsafe(); \
281 NAME##_set_unsafe(TYPE value) \
283 TYPE old_value = NAME##_get_unsafe(); \
284 pthread_setspecific(NAME##_key, value); \
288 static OVS_UNUSED TYPE \
289 NAME##_set(TYPE value) \
292 return NAME##_set_unsafe(value); \
295 /* Convenient once-only execution.
301 * POSIX provides pthread_once_t and pthread_once() as primitives for running a
302 * set of code only once per process execution. They are used like this:
304 * static void run_once(void) { ...initialization... }
305 * static pthread_once_t once = PTHREAD_ONCE_INIT;
307 * pthread_once(&once, run_once);
309 * pthread_once() does not allow passing any parameters to the initialization
310 * function, which is often inconvenient, because it means that the function
311 * can only access data declared at file scope.
317 * Use ovsthread_once, like this, instead:
319 * static struct ovsthread_once once = OVSTHREAD_ONCE_INITIALIZER;
321 * if (ovsthread_once_start(&once)) {
322 * ...initialization...
323 * ovsthread_once_done(&once);
327 struct ovsthread_once {
329 pthread_mutex_t mutex;
332 #define OVSTHREAD_ONCE_INITIALIZER \
334 ATOMIC_VAR_INIT(false), \
335 PTHREAD_ADAPTIVE_MUTEX_INITIALIZER, \
338 static inline bool ovsthread_once_start(struct ovsthread_once *);
339 void ovsthread_once_done(struct ovsthread_once *once) OVS_RELEASES(once);
341 bool ovsthread_once_start__(struct ovsthread_once *);
344 ovsthread_once_is_done__(const struct ovsthread_once *once)
348 atomic_read_explicit(&once->done, &done, memory_order_relaxed);
352 /* Returns true if this is the first call to ovsthread_once_start() for
353 * 'once'. In this case, the caller should perform whatever initialization
354 * actions it needs to do, then call ovsthread_once_done() for 'once'.
356 * Returns false if this is not the first call to ovsthread_once_start() for
357 * 'once'. In this case, the call will not return until after
358 * ovsthread_once_done() has been called. */
360 ovsthread_once_start(struct ovsthread_once *once)
362 return OVS_UNLIKELY(!ovsthread_once_is_done__(once)
363 && !ovsthread_once_start__(once));
367 #define ovsthread_once_start(ONCE) \
368 ((ONCE)->done ? false : ({ OVS_ACQUIRE(ONCE); true; }))
371 void assert_single_threaded(const char *where);
372 #define assert_single_threaded() assert_single_threaded(SOURCE_LOCATOR)
374 pid_t xfork(const char *where);
375 #define xfork() xfork(SOURCE_LOCATOR)
377 void forbid_forking(const char *reason);
380 #endif /* ovs-thread.h */