]> git.saurik.com Git - apple/libplatform.git/blob - src/os/semaphore.c
d805afc5e5769db2609c9974a71c7157b73076f3
[apple/libplatform.git] / src / os / semaphore.c
1 /*
2 * Copyright (c) 2008-2013 Apple Inc. All rights reserved.
3 *
4 * @APPLE_APACHE_LICENSE_HEADER_START@
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 *
18 * @APPLE_APACHE_LICENSE_HEADER_END@
19 */
20
21 #include "os/internal.h"
22 #include <mach/mach_init.h>
23 #include <mach/semaphore.h>
24 #include <mach/task.h>
25 #include <mach/thread_switch.h>
26
27 #define OS_VERIFY_MIG(x, msg) do { \
28 if (unlikely((x) == MIG_REPLY_MISMATCH)) { \
29 __LIBPLATFORM_CLIENT_CRASH__(x, msg); \
30 } \
31 } while (0)
32
33 #define OS_SEMAPHORE_VERIFY_KR(x, msg) do { \
34 if (unlikely(x)) { \
35 __LIBPLATFORM_CLIENT_CRASH__(x, msg); \
36 } \
37 } while (0)
38
39 os_semaphore_t
40 _os_semaphore_create(void)
41 {
42 semaphore_t s4;
43 kern_return_t kr;
44 while (unlikely(kr = semaphore_create(mach_task_self(), &s4,
45 SYNC_POLICY_FIFO, 0))) {
46 OS_VERIFY_MIG(kr, "Allocating semaphore failed with MIG_REPLY_MISMATCH");
47 thread_switch(MACH_PORT_NULL, SWITCH_OPTION_WAIT, 100);
48 }
49 return (os_semaphore_t)s4;
50 }
51
52 void
53 _os_semaphore_dispose(os_semaphore_t sema)
54 {
55 semaphore_t s4 = (semaphore_t)sema;
56 kern_return_t kr = semaphore_destroy(mach_task_self(), s4);
57 OS_SEMAPHORE_VERIFY_KR(kr, "Destroying semaphore failed");
58 }
59
60 void
61 _os_semaphore_signal(os_semaphore_t sema)
62 {
63 semaphore_t s4 = (semaphore_t)sema;
64 kern_return_t kr = semaphore_signal(s4);
65 OS_SEMAPHORE_VERIFY_KR(kr, "Signaling semaphore failed");
66 }
67
68 void
69 _os_semaphore_wait(os_semaphore_t sema)
70 {
71 semaphore_t s4 = (semaphore_t)sema;
72 kern_return_t kr;
73 do {
74 kr = semaphore_wait(s4);
75 } while (unlikely(kr == KERN_ABORTED));
76 OS_SEMAPHORE_VERIFY_KR(kr, "Waiting on semaphore failed");
77 }