1 // ---------------------------------------------------------------------------- 2 // 3 // Copyright (C) 2008-2018 Fons Adriaensen <fons@linuxaudio.org> 4 // 5 // This program is free software; you can redistribute it and/or modify 6 // it under the terms of the GNU General Public License as published by 7 // the Free Software Foundation; either version 3 of the License, or 8 // (at your option) any later version. 9 // 10 // This program is distributed in the hope that it will be useful, 11 // but WITHOUT ANY WARRANTY; without even the implied warranty of 12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 // GNU General Public License for more details. 14 // 15 // You should have received a copy of the GNU General Public License 16 // along with this program. If not, see <http://www.gnu.org/licenses/>. 17 // 18 // ---------------------------------------------------------------------------- 19 20 21 #ifndef _POSIXTHR_H 22 #define _POSIXTHR_H 23 24 25 #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) 26 27 #include <stdlib.h> 28 #include <pthread.h> 29 #include <semaphore.h> 30 31 32 class P_sema 33 { 34 public: 35 P_sema(void)36 P_sema (void) { if (sem_init (&_sema, 0, 0)) abort (); } ~P_sema(void)37 ~P_sema (void) { sem_destroy (&_sema); } 38 P_sema (const P_sema&); 39 P_sema& operator= (const P_sema&); 40 post(void)41 int post (void) { return sem_post (&_sema); } wait(void)42 int wait (void) { return sem_wait (&_sema); } trywait(void)43 int trywait (void) { return sem_trywait (&_sema); } getvalue(void)44 int getvalue (void) { int n; sem_getvalue (&_sema, &n); return n; } 45 46 private: 47 48 sem_t _sema; 49 }; 50 51 52 class P_mutex 53 { 54 public: 55 P_mutex(void)56 P_mutex (void) { if (pthread_mutex_init (&_mutex, 0)) abort (); } ~P_mutex(void)57 ~P_mutex (void) { pthread_mutex_destroy (&_mutex); } 58 P_mutex (const P_mutex&); 59 P_mutex& operator= (const P_mutex&); 60 lock(void)61 int lock (void) { return pthread_mutex_lock (&_mutex); } unlock(void)62 int unlock (void){ return pthread_mutex_unlock (&_mutex); } trylock(void)63 int trylock (void) { return pthread_mutex_trylock (&_mutex); } 64 65 private: 66 67 pthread_mutex_t _mutex; 68 }; 69 70 71 class P_thread 72 { 73 public: 74 75 P_thread (void); 76 virtual ~P_thread (void); 77 P_thread (const P_thread&); 78 P_thread& operator=(const P_thread&); 79 sepuku(void)80 void sepuku (void) { pthread_cancel (_ident); } 81 82 virtual void thr_main (void) = 0; 83 virtual int thr_start (int policy, int priority, size_t stacksize = 0); 84 85 private: 86 87 pthread_t _ident; 88 }; 89 90 91 #endif // __linux__ 92 93 94 #endif // _POSIXTHR_H 95 96