2 * Copyright (C) 2010-2014 Paul Davis <paul@linuxaudiosystems.com>
3 * Copyright (C) 2015-2017 Robin Gareus <robin@gareus.org>
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 2 of the License, or
8 * (at your option) any later version.
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.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "pbd/semutils.h"
21 #include "pbd/failed_constructor.h"
25 Semaphore::Semaphore (const char* name, int val)
27 #ifdef WINDOWS_SEMAPHORE
28 if ((_sem = CreateSemaphore(NULL, val, 32767, name)) == NULL) {
29 throw failed_constructor ();
33 if ((_sem = sem_open (name, O_CREAT, 0600, val)) == (sem_t*) SEM_FAILED) {
34 throw failed_constructor ();
37 /* this semaphore does not exist for IPC */
39 if (sem_unlink (name)) {
40 throw failed_constructor ();
44 (void) name; /* stop gcc warning on !Apple systems */
46 if (sem_init (&_sem, 0, val)) {
47 throw failed_constructor ();
52 Semaphore::~Semaphore ()
54 #ifdef WINDOWS_SEMAPHORE
57 sem_close (ptr_to_sem());
61 #ifdef WINDOWS_SEMAPHORE
66 // non-zero on success, opposite to posix
67 return !ReleaseSemaphore(_sem, 1, NULL);
74 result = WaitForSingleObject(_sem, INFINITE);
75 return (result == WAIT_OBJECT_0);
85 result = WaitForSingleObject(_sem, 0);
86 } while (result == WAIT_OBJECT_0);