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
32DE_STATIC_ASSERT(sizeof(deSemaphore) >= sizeof(sem_t*));
33
34deSemaphore deSemaphore_create (int initialValue, const deSemaphoreAttributes* attributes)
35{
36	sem_t*	sem	= (sem_t*)deMalloc(sizeof(sem_t));
37
38	DE_UNREF(attributes);
39
40	if (!sem)
41		return 0;
42
43	if (sem_init(sem, 0, initialValue) != 0)
44	{
45		deFree(sem);
46		return 0;
47	}
48
49	return (deSemaphore)sem;
50}
51
52void deSemaphore_destroy (deSemaphore semaphore)
53{
54	sem_t* sem = (sem_t*)semaphore;
55	DE_ASSERT(sem);
56	sem_destroy(sem);
57	deFree(sem);
58}
59
60void deSemaphore_increment (deSemaphore semaphore)
61{
62	sem_t*	sem	= (sem_t*)semaphore;
63	int		ret	= sem_post(sem);
64	DE_ASSERT(ret == 0);
65	DE_UNREF(ret);
66}
67
68void deSemaphore_decrement (deSemaphore semaphore)
69{
70	sem_t*	sem	= (sem_t*)semaphore;
71	int		ret	= sem_wait(sem);
72	DE_ASSERT(ret == 0);
73	DE_UNREF(ret);
74}
75
76deBool deSemaphore_tryDecrement (deSemaphore semaphore)
77{
78	sem_t* sem = (sem_t*)semaphore;
79	DE_ASSERT(sem);
80	return (sem_trywait(sem) == 0);
81}
82
83#endif /* DE_OS */
84