|
|
| version 1.5, 2001/03/10 16:34:35 | version 1.36, 2020/12/15 11:28:40 |
|---|---|
| Line 1 | Line 1 |
| /* | /** @file |
| Parser | Parser: mutex & helpers decls. |
| Copyright (c) 2001 ArtLebedev Group (http://www.artlebedev.com) | |
| Author: Alexander Petrosyan <paf@design.ru> | |
| $Id$ | Copyright (c) 2001-2017 Art. Lebedev Studio (http://www.artlebedev.com) |
| Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru) | |
| */ | */ |
| #ifndef PA_THREADS_H | #ifndef PA_THREADS_H |
| #define PA_THREADS_H | #define PA_THREADS_H |
| #ifdef HAVE_CONFIG_H | #define IDENT_PA_THREADS_H "$Id$" |
| # include "pa_config.h" | |
| #endif | |
| #include "pa_config_includes.h" | |
| #include "pa_types.h" | #include "pa_types.h" |
| #ifdef _MSC_VER | |
| #include <windows.h> | |
| #endif | |
| /// get caller thread ID | |
| uint pa_get_thread_id(); | |
| #ifdef MULTITHREAD | class AutoSYNCHRONIZED; |
| /// simple semaphore object | |
| class Mutex { | class Mutex { |
| uint handle; | friend class AutoSYNCHRONIZED; |
| #ifdef _MSC_VER | |
| HANDLE handle; | |
| #else | |
| pthread_mutex_t handle; | |
| #endif | |
| public: | public: |
| Mutex(); | Mutex(); |
| ~Mutex(); | ~Mutex(); |
| private: // for AutoSYNCHRONIZED | |
| void acquire(); | void acquire(); |
| void release(); | void release(); |
| }; | }; |
| extern Mutex global_mutex; | extern Mutex global_mutex; |
| /** | |
| Helper to ensure paired Mutex::acquire() and Mutex::release(). | |
| Use it with SYNCHRONIZED macro | |
| */ | |
| class AutoSYNCHRONIZED { | class AutoSYNCHRONIZED { |
| bool thread_safe; | |
| public: | public: |
| AutoSYNCHRONIZED(bool athread_safe) : thread_safe(athread_safe) { | AutoSYNCHRONIZED() { global_mutex.acquire(); } |
| if(thread_safe) | ~AutoSYNCHRONIZED() { global_mutex.release(); } |
| global_mutex.acquire(); | }; |
| } | |
| ~AutoSYNCHRONIZED() { | |
| if(thread_safe) | |
| global_mutex.release(); | |
| } | |
| } | |
| #define SYNCHRONIZED(athread_safe) AutoSYNCHRONIZED autoSYNCHRONIZED(athread_safe) | |
| #else // not MULTITHREAD-ed | |
| #define SYNCHRONIZED(athread_safe) /* do nothing */ | |
| #endif | /** |
| put it to first line of a function to ensure thread safety. | |
| @verbatim | |
| void someclass::somefunc(...) { SYNCHRONIZED; | |
| ... | |
| } | |
| @endverbatim | |
| WARNING: don't use THROW or PTHROW with such thread safety mechanizm - | |
| longjmp would leave global_mutex acquired, which is wrong! | |
| */ | |
| #define SYNCHRONIZED AutoSYNCHRONIZED autoSYNCHRONIZED | |
| #endif | #endif |