1 /*-------------------------------------------------------------------------
2  * drawElements Thread Library
3  * ---------------------------
4  *
5  * Copyright 2014 The Android Open Source Project
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  *//*!
20  * \file
21  * \brief Unix implementation of semaphore.
22  *//*--------------------------------------------------------------------*/
23 
24 #include "deSemaphore.h"
25 
26 #if (DE_OS == DE_OS_UNIX || DE_OS == DE_OS_ANDROID || DE_OS == DE_OS_SYMBIAN)
27 
28 #include "deMemory.h"
29 
30 #include <semaphore.h>
31 
32 DE_STATIC_ASSERT(sizeof(deSemaphore) >= sizeof(sem_t*));
33 
deSemaphore_create(int initialValue,const deSemaphoreAttributes * attributes)34 deSemaphore deSemaphore_create (int initialValue, const deSemaphoreAttributes* attributes)
35 {
36 	sem_t*	sem	= (sem_t*)deMalloc(sizeof(sem_t));
37 
38 	DE_UNREF(attributes);
39 	DE_ASSERT(initialValue >= 0);
40 
41 	if (!sem)
42 		return 0;
43 
44 	if (sem_init(sem, 0, (unsigned int)initialValue) != 0)
45 	{
46 		deFree(sem);
47 		return 0;
48 	}
49 
50 	return (deSemaphore)sem;
51 }
52 
deSemaphore_destroy(deSemaphore semaphore)53 void deSemaphore_destroy (deSemaphore semaphore)
54 {
55 	sem_t* sem = (sem_t*)semaphore;
56 	DE_ASSERT(sem);
57 	sem_destroy(sem);
58 	deFree(sem);
59 }
60 
deSemaphore_increment(deSemaphore semaphore)61 void deSemaphore_increment (deSemaphore semaphore)
62 {
63 	sem_t*	sem	= (sem_t*)semaphore;
64 	int		ret	= sem_post(sem);
65 	DE_ASSERT(ret == 0);
66 	DE_UNREF(ret);
67 }
68 
deSemaphore_decrement(deSemaphore semaphore)69 void deSemaphore_decrement (deSemaphore semaphore)
70 {
71 	sem_t*	sem	= (sem_t*)semaphore;
72 	int		ret	= sem_wait(sem);
73 	DE_ASSERT(ret == 0);
74 	DE_UNREF(ret);
75 }
76 
deSemaphore_tryDecrement(deSemaphore semaphore)77 deBool deSemaphore_tryDecrement (deSemaphore semaphore)
78 {
79 	sem_t* sem = (sem_t*)semaphore;
80 	DE_ASSERT(sem);
81 	return (sem_trywait(sem) == 0);
82 }
83 
84 #endif /* DE_OS */
85