1 /*
2 * Copyright (c) 2017 Intel Corporation
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <zephyr/ztest.h>
8 #include <zephyr/kernel.h>
9 #include <cmsis_os.h>
10
11 #define TIMEOUT 500
12
13 osSemaphoreDef(semaphore_1);
14
thread_sema(void const * arg)15 void thread_sema(void const *arg)
16 {
17 int tokens_available;
18
19 /* Try taking semaphore immediately when it is not available */
20 tokens_available = osSemaphoreWait((osSemaphoreId)arg, 0);
21 zassert_true(tokens_available == 0,
22 "Semaphore acquired unexpectedly!");
23
24 /* Try taking semaphore after a TIMEOUT, but before release */
25 tokens_available = osSemaphoreWait((osSemaphoreId)arg, TIMEOUT - 100);
26 zassert_true(tokens_available == 0,
27 "Semaphore acquired unexpectedly!");
28
29 /* This delay ensures that the semaphore gets released by the other
30 * thread in the meantime
31 */
32 osDelay(TIMEOUT - 100);
33
34 /* Now that the semaphore is free, it should be possible to acquire
35 * and release it.
36 */
37 tokens_available = osSemaphoreWait((osSemaphoreId)arg, 0);
38 zassert_true(tokens_available > 0);
39
40 zassert_true(osSemaphoreRelease((osSemaphoreId)arg) == osOK,
41 "Semaphore release failure");
42
43 /* Try releasing when no semaphore is obtained */
44 zassert_true(osSemaphoreRelease((osSemaphoreId)arg) == osErrorResource,
45 "Semaphore released unexpectedly!");
46 }
47
48 osThreadDef(thread_sema, osPriorityNormal, 1, 0);
49
ZTEST(cmsis_semaphore,test_semaphore)50 ZTEST(cmsis_semaphore, test_semaphore)
51 {
52 osThreadId id;
53 osStatus status;
54 osSemaphoreId semaphore_id;
55
56 semaphore_id = osSemaphoreCreate(osSemaphore(semaphore_1), 1);
57 zassert_true(semaphore_id != NULL, "semaphore creation failed");
58
59 id = osThreadCreate(osThread(thread_sema), semaphore_id);
60 zassert_true(id != NULL, "Thread creation failed");
61
62 zassert_true(osSemaphoreWait(semaphore_id, osWaitForever) > 0,
63 "Semaphore wait failure");
64
65 /* wait for spawn thread to take action */
66 osDelay(TIMEOUT);
67
68 /* Release the semaphore to be used by the other thread */
69 status = osSemaphoreRelease(semaphore_id);
70 zassert_true(status == osOK, "Semaphore release failure");
71
72 osDelay(TIMEOUT);
73
74 status = osSemaphoreDelete(semaphore_id);
75 zassert_true(status == osOK, "semaphore delete failure");
76 }
77 ZTEST_SUITE(cmsis_semaphore, NULL, NULL, NULL, NULL, NULL);
78