/simpletypesystem/trunk

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/simpletypesystem/trunk
128 by Gustav Hartvigsson
* Removed blasted #pragma message s from Thread.h
1
/* -*- mode: c; tab-width: 2; indent-tabs-mode: nil; -*-
2
Copyright (c) 2012 Marcus Geelnard
3
Copyright (c) 2013-2014 Evan Nemerson
4
5
This software is provided 'as-is', without any express or implied
6
warranty. In no event will the authors be held liable for any damages
7
arising from the use of this software.
8
9
Permission is granted to anyone to use this software for any purpose,
10
including commercial applications, and to alter it and redistribute it
11
freely, subject to the following restrictions:
12
13
    1. The origin of this software must not be misrepresented; you must not
14
    claim that you wrote the original software. If you use this software
15
    in a product, an acknowledgment in the product documentation would be
16
    appreciated but is not required.
17
18
    2. Altered source versions must be plainly marked as such, and must not be
19
    misrepresented as being the original software.
20
21
    3. This notice may not be removed or altered from any source
22
    distribution.
23
*/
24
25
#ifndef _TINYCTHREAD_H_
26
#define _TINYCTHREAD_H_
27
28
#ifdef __cplusplus
29
extern "C" {
30
#endif
31
32
/**
33
* @file
34
* @mainpage TinyCThread API Reference
35
*
36
* @section intro_sec Introduction
37
* TinyCThread is a minimal, portable implementation of basic threading
38
* classes for C.
39
*
40
* They closely mimic the functionality and naming of the C11 standard, and
41
* should be easily replaceable with the corresponding standard variants.
42
*
43
* @section port_sec Portability
44
* The Win32 variant uses the native Win32 API for implementing the thread
45
* classes, while for other systems, the POSIX threads API (pthread) is used.
46
*
47
* @section misc_sec Miscellaneous
48
* The following special keywords are available: #_Thread_local.
49
*
50
* For more detailed information, browse the different sections of this
51
* documentation. A good place to start is:
52
* tinycthread.h.
53
*/
54
55
/* Which platform are we on? */
56
#if !defined(_TTHREAD_PLATFORM_DEFINED_)
57
  #if defined(_WIN32) || defined(__WIN32__) || defined(__WINDOWS__)
58
    #define _TTHREAD_WIN32_
59
  #else
60
    #define _TTHREAD_POSIX_
61
  #endif
62
  #define _TTHREAD_PLATFORM_DEFINED_
63
#endif
64
65
/* Activate some POSIX functionality (e.g. clock_gettime and recursive mutexes) */
66
#if defined(_TTHREAD_POSIX_)
67
  #undef _FEATURES_H
68
  #if !defined(_GNU_SOURCE)
69
    #define _GNU_SOURCE
70
  #endif
71
  #if !defined(_POSIX_C_SOURCE) || ((_POSIX_C_SOURCE - 0) < 199309L)
72
    #undef _POSIX_C_SOURCE
73
    #define _POSIX_C_SOURCE 199309L
74
  #endif
75
  #if !defined(_XOPEN_SOURCE) || ((_XOPEN_SOURCE - 0) < 500)
76
    #undef _XOPEN_SOURCE
77
    #define _XOPEN_SOURCE 500
78
  #endif
79
#endif
80
81
/* Generic includes */
82
#include <time.h>
83
84
/* Platform specific includes */
85
#if defined(_TTHREAD_POSIX_)
86
  #include <pthread.h>
87
#elif defined(_TTHREAD_WIN32_)
88
  #ifndef WIN32_LEAN_AND_MEAN
89
    #define WIN32_LEAN_AND_MEAN
90
    #define __UNDEF_LEAN_AND_MEAN
91
  #endif
92
  #include <windows.h>
93
  #ifdef __UNDEF_LEAN_AND_MEAN
94
    #undef WIN32_LEAN_AND_MEAN
95
    #undef __UNDEF_LEAN_AND_MEAN
96
  #endif
97
#endif
98
99
/* Compiler-specific information */
100
#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L
101
  #define TTHREAD_NORETURN _Noreturn
102
#elif defined(__GNUC__)
103
  #define TTHREAD_NORETURN __attribute__((__noreturn__))
104
#else
105
  #define TTHREAD_NORETURN
106
#endif
107
108
/* If TIME_UTC is missing, provide it and provide a wrapper for
109
   timespec_get. */
110
#ifndef TIME_UTC
111
#define TIME_UTC 1
112
#define _TTHREAD_EMULATE_TIMESPEC_GET_
113
114
#if defined(_TTHREAD_WIN32_)
115
struct _tthread_timespec {
116
  time_t tv_sec;
117
  long   tv_nsec;
118
};
119
#define timespec _tthread_timespec
120
#endif
121
122
int _tthread_timespec_get(struct timespec *ts, int base);
123
#define timespec_get _tthread_timespec_get
124
#endif
125
126
/** TinyCThread version (major number). */
127
#define TINYCTHREAD_VERSION_MAJOR 1
128
/** TinyCThread version (minor number). */
129
#define TINYCTHREAD_VERSION_MINOR 2
130
/** TinyCThread version (full version). */
131
#define TINYCTHREAD_VERSION (TINYCTHREAD_VERSION_MAJOR * 100 + TINYCTHREAD_VERSION_MINOR)
132
133
/**
134
* @def _Thread_local
135
* Thread local storage keyword.
136
* A variable that is declared with the @c _Thread_local keyword makes the
137
* value of the variable local to each thread (known as thread-local storage,
138
* or TLS). Example usage:
139
* @code
140
* // This variable is local to each thread.
141
* _Thread_local int variable;
142
* @endcode
143
* @note The @c _Thread_local keyword is a macro that maps to the corresponding
144
* compiler directive (e.g. @c __declspec(thread)).
145
* @note This directive is currently not supported on Mac OS X (it will give
146
* a compiler error), since compile-time TLS is not supported in the Mac OS X
147
* executable format. Also, some older versions of MinGW (before GCC 4.x) do
148
* not support this directive, nor does the Tiny C Compiler.
149
* @hideinitializer
150
*/
151
152
#if !(defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201102L)) && !defined(_Thread_local)
153
 #if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
154
  #define _Thread_local __thread
155
 #else
156
  #define _Thread_local __declspec(thread)
157
 #endif
158
#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && (((__GNUC__ << 8) | __GNUC_MINOR__) < ((4 << 8) | 9))
159
 #define _Thread_local __thread
160
#endif
161
162
/* Macros */
163
#if defined(_TTHREAD_WIN32_)
164
#define TSS_DTOR_ITERATIONS (4)
165
#else
166
#define TSS_DTOR_ITERATIONS PTHREAD_DESTRUCTOR_ITERATIONS
167
#endif
168
169
/* Function return values */
170
#define thrd_error    0 /**< The requested operation failed */
171
#define thrd_success  1 /**< The requested operation succeeded */
172
#define thrd_timedout 2 /**< The time specified in the call was reached without acquiring the requested resource */
173
#define thrd_busy     3 /**< The requested operation failed because a tesource requested by a test and return function is already in use */
174
#define thrd_nomem    4 /**< The requested operation failed because it was unable to allocate memory */
175
176
/* Mutex types */
177
#define mtx_plain     0
178
#define mtx_timed     1
179
#define mtx_recursive 2
180
181
/* Mutex */
182
#if defined(_TTHREAD_WIN32_)
183
typedef struct {
184
  union {
185
    CRITICAL_SECTION cs;      /* Critical section handle (used for non-timed mutexes) */
186
    HANDLE mut;               /* Mutex handle (used for timed mutex) */
187
  } mHandle;                  /* Mutex handle */
188
  int mAlreadyLocked;         /* TRUE if the mutex is already locked */
189
  int mRecursive;             /* TRUE if the mutex is recursive */
190
  int mTimed;                 /* TRUE if the mutex is timed */
191
} mtx_t;
192
#else
193
typedef pthread_mutex_t mtx_t;
194
#endif
195
196
/** Create a mutex object.
197
* @param mtx A mutex object.
198
* @param type Bit-mask that must have one of the following six values:
199
*   @li @c mtx_plain for a simple non-recursive mutex
200
*   @li @c mtx_timed for a non-recursive mutex that supports timeout
201
*   @li @c mtx_plain | @c mtx_recursive (same as @c mtx_plain, but recursive)
202
*   @li @c mtx_timed | @c mtx_recursive (same as @c mtx_timed, but recursive)
203
* @return @ref thrd_success on success, or @ref thrd_error if the request could
204
* not be honored.
205
*/
206
int mtx_init(mtx_t *mtx, int type);
207
208
/** Release any resources used by the given mutex.
209
* @param mtx A mutex object.
210
*/
211
void mtx_destroy(mtx_t *mtx);
212
213
/** Lock the given mutex.
214
* Blocks until the given mutex can be locked. If the mutex is non-recursive, and
215
* the calling thread already has a lock on the mutex, this call will block
216
* forever.
217
* @param mtx A mutex object.
218
* @return @ref thrd_success on success, or @ref thrd_error if the request could
219
* not be honored.
220
*/
221
int mtx_lock(mtx_t *mtx);
222
223
/** NOT YET IMPLEMENTED.
224
*/
225
int mtx_timedlock(mtx_t *mtx, const struct timespec *ts);
226
227
/** Try to lock the given mutex.
228
* The specified mutex shall support either test and return or timeout. If the
229
* mutex is already locked, the function returns without blocking.
230
* @param mtx A mutex object.
231
* @return @ref thrd_success on success, or @ref thrd_busy if the resource
232
* requested is already in use, or @ref thrd_error if the request could not be
233
* honored.
234
*/
235
int mtx_trylock(mtx_t *mtx);
236
237
/** Unlock the given mutex.
238
* @param mtx A mutex object.
239
* @return @ref thrd_success on success, or @ref thrd_error if the request could
240
* not be honored.
241
*/
242
int mtx_unlock(mtx_t *mtx);
243
244
/* Condition variable */
245
#if defined(_TTHREAD_WIN32_)
246
typedef struct {
247
  HANDLE mEvents[2];                  /* Signal and broadcast event HANDLEs. */
248
  unsigned int mWaitersCount;         /* Count of the number of waiters. */
249
  CRITICAL_SECTION mWaitersCountLock; /* Serialize access to mWaitersCount. */
250
} cnd_t;
251
#else
252
typedef pthread_cond_t cnd_t;
253
#endif
254
255
/** Create a condition variable object.
256
* @param cond A condition variable object.
257
* @return @ref thrd_success on success, or @ref thrd_error if the request could
258
* not be honored.
259
*/
260
int cnd_init(cnd_t *cond);
261
262
/** Release any resources used by the given condition variable.
263
* @param cond A condition variable object.
264
*/
265
void cnd_destroy(cnd_t *cond);
266
267
/** Signal a condition variable.
268
* Unblocks one of the threads that are blocked on the given condition variable
269
* at the time of the call. If no threads are blocked on the condition variable
270
* at the time of the call, the function does nothing and return success.
271
* @param cond A condition variable object.
272
* @return @ref thrd_success on success, or @ref thrd_error if the request could
273
* not be honored.
274
*/
275
int cnd_signal(cnd_t *cond);
276
277
/** Broadcast a condition variable.
278
* Unblocks all of the threads that are blocked on the given condition variable
279
* at the time of the call. If no threads are blocked on the condition variable
280
* at the time of the call, the function does nothing and return success.
281
* @param cond A condition variable object.
282
* @return @ref thrd_success on success, or @ref thrd_error if the request could
283
* not be honored.
284
*/
285
int cnd_broadcast(cnd_t *cond);
286
287
/** Wait for a condition variable to become signaled.
288
* The function atomically unlocks the given mutex and endeavors to block until
289
* the given condition variable is signaled by a call to cnd_signal or to
290
* cnd_broadcast. When the calling thread becomes unblocked it locks the mutex
291
* before it returns.
292
* @param cond A condition variable object.
293
* @param mtx A mutex object.
294
* @return @ref thrd_success on success, or @ref thrd_error if the request could
295
* not be honored.
296
*/
297
int cnd_wait(cnd_t *cond, mtx_t *mtx);
298
299
/** Wait for a condition variable to become signaled.
300
* The function atomically unlocks the given mutex and endeavors to block until
301
* the given condition variable is signaled by a call to cnd_signal or to
302
* cnd_broadcast, or until after the specified time. When the calling thread
303
* becomes unblocked it locks the mutex before it returns.
304
* @param cond A condition variable object.
305
* @param mtx A mutex object.
306
* @param xt A point in time at which the request will time out (absolute time).
307
* @return @ref thrd_success upon success, or @ref thrd_timeout if the time
308
* specified in the call was reached without acquiring the requested resource, or
309
* @ref thrd_error if the request could not be honored.
310
*/
311
int cnd_timedwait(cnd_t *cond, mtx_t *mtx, const struct timespec *ts);
312
313
/* Thread */
314
#if defined(_TTHREAD_WIN32_)
315
typedef HANDLE thrd_t;
316
#else
317
typedef pthread_t thrd_t;
318
#endif
319
320
/** Thread start function.
321
* Any thread that is started with the @ref thrd_create() function must be
322
* started through a function of this type.
323
* @param arg The thread argument (the @c arg argument of the corresponding
324
*        @ref thrd_create() call).
325
* @return The thread return value, which can be obtained by another thread
326
* by using the @ref thrd_join() function.
327
*/
328
typedef int (*thrd_start_t)(void *arg);
329
330
/** Create a new thread.
331
* @param thr Identifier of the newly created thread.
332
* @param func A function pointer to the function that will be executed in
333
*        the new thread.
334
* @param arg An argument to the thread function.
335
* @return @ref thrd_success on success, or @ref thrd_nomem if no memory could
336
* be allocated for the thread requested, or @ref thrd_error if the request
337
* could not be honored.
338
* @note A thread’s identifier may be reused for a different thread once the
339
* original thread has exited and either been detached or joined to another
340
* thread.
341
*/
342
int thrd_create(thrd_t *thr, thrd_start_t func, void *arg);
343
344
/** Identify the calling thread.
345
* @return The identifier of the calling thread.
346
*/
347
thrd_t thrd_current(void);
348
349
/** Dispose of any resources allocated to the thread when that thread exits.
350
 * @return thrd_success, or thrd_error on error
351
*/
352
int thrd_detach(thrd_t thr);
353
354
/** Compare two thread identifiers.
355
* The function determines if two thread identifiers refer to the same thread.
356
* @return Zero if the two thread identifiers refer to different threads.
357
* Otherwise a nonzero value is returned.
358
*/
359
int thrd_equal(thrd_t thr0, thrd_t thr1);
360
361
/** Terminate execution of the calling thread.
362
* @param res Result code of the calling thread.
363
*/
364
TTHREAD_NORETURN void thrd_exit(int res);
365
366
/** Wait for a thread to terminate.
367
* The function joins the given thread with the current thread by blocking
368
* until the other thread has terminated.
369
* @param thr The thread to join with.
370
* @param res If this pointer is not NULL, the function will store the result
371
*        code of the given thread in the integer pointed to by @c res.
372
* @return @ref thrd_success on success, or @ref thrd_error if the request could
373
* not be honored.
374
*/
375
int thrd_join(thrd_t thr, int *res);
376
377
/** Put the calling thread to sleep.
378
* Suspend execution of the calling thread.
379
* @param duration  Interval to sleep for
380
* @param remaining If non-NULL, this parameter will hold the remaining
381
*                  time until time_point upon return. This will
382
*                  typically be zero, but if the thread was woken up
383
*                  by a signal that is not ignored before duration was
384
*                  reached @c remaining will hold a positive time.
385
* @return 0 (zero) on successful sleep, -1 if an interrupt occurred,
386
*         or a negative value if the operation fails.
387
*/
388
int thrd_sleep(const struct timespec *duration, struct timespec *remaining);
389
390
/** Yield execution to another thread.
391
* Permit other threads to run, even if the current thread would ordinarily
392
* continue to run.
393
*/
394
void thrd_yield(void);
395
396
/* Thread local storage */
397
#if defined(_TTHREAD_WIN32_)
398
typedef DWORD tss_t;
399
#else
400
typedef pthread_key_t tss_t;
401
#endif
402
403
/** Destructor function for a thread-specific storage.
404
* @param val The value of the destructed thread-specific storage.
405
*/
406
typedef void (*tss_dtor_t)(void *val);
407
408
/** Create a thread-specific storage.
409
* @param key The unique key identifier that will be set if the function is
410
*        successful.
411
* @param dtor Destructor function. This can be NULL.
412
* @return @ref thrd_success on success, or @ref thrd_error if the request could
413
* not be honored.
414
* @note On Windows, the @c dtor will definitely be called when
415
* appropriate for threads created with @ref thrd_create.  It will be
416
* called for other threads in most cases, the possible exception being
417
* for DLLs loaded with LoadLibraryEx.  In order to be certain, you
418
* should use @ref thrd_create whenever possible.
419
*/
420
int tss_create(tss_t *key, tss_dtor_t dtor);
421
422
/** Delete a thread-specific storage.
423
* The function releases any resources used by the given thread-specific
424
* storage.
425
* @param key The key that shall be deleted.
426
*/
427
void tss_delete(tss_t key);
428
429
/** Get the value for a thread-specific storage.
430
* @param key The thread-specific storage identifier.
431
* @return The value for the current thread held in the given thread-specific
432
* storage.
433
*/
434
void *tss_get(tss_t key);
435
436
/** Set the value for a thread-specific storage.
437
* @param key The thread-specific storage identifier.
438
* @param val The value of the thread-specific storage to set for the current
439
*        thread.
440
* @return @ref thrd_success on success, or @ref thrd_error if the request could
441
* not be honored.
442
*/
443
int tss_set(tss_t key, void *val);
444
445
#if defined(_TTHREAD_WIN32_)
446
  typedef struct {
447
    LONG volatile status;
448
    CRITICAL_SECTION lock;
449
  } once_flag;
450
  #define ONCE_FLAG_INIT {0,}
451
#else
452
  #define once_flag pthread_once_t
453
  #define ONCE_FLAG_INIT PTHREAD_ONCE_INIT
454
#endif
455
456
/** Invoke a callback exactly once
457
 * @param flag Flag used to ensure the callback is invoked exactly
458
 *        once.
459
 * @param func Callback to invoke.
460
 */
461
#if defined(_TTHREAD_WIN32_)
462
  void call_once(once_flag *flag, void (*func)(void));
463
#else
464
  #define call_once(flag,func) pthread_once(flag,func)
465
#endif
466
467
#ifdef __cplusplus
468
}
469
#endif
470
471
#endif /* _TINYTHREAD_H_ */