1 /*
2 * Copyright (c) 2020 Nanjing Xiaoxiongpai Intelligent Technology Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include <stdio.h>
17 #include <string.h>
18 #include <unistd.h>
19
20 #include "cmsis_os2.h"
21 #include "ohos_init.h"
22
23 osMutexId_t g_mutexId;
24
25 #define THREAD_STACK_SIZE (1024 * 4)
26 #define HIGH_THREAD_PRIO 24
27 #define MID_THREAD_PRIO 25
28 #define LOW_THREAD_PRIO 26
29
30 #define THREAD_DELAY_3S 300
31 #define THREAD_DELAY_1S 100
32
HighPrioThread(void)33 void HighPrioThread(void)
34 {
35 // wait 1s until start actual work
36 osDelay(THREAD_DELAY_1S);
37
38 while (1) {
39 // try to acquire mutex
40 osMutexAcquire(g_mutexId, osWaitForever);
41
42 printf("HighPrioThread is running.\n");
43 osDelay(THREAD_DELAY_3S);
44 osMutexRelease(g_mutexId);
45 }
46 }
47
MidPrioThread(void)48 void MidPrioThread(void)
49 {
50 // wait 1s until start actual work
51 osDelay(THREAD_DELAY_1S);
52
53 while (1) {
54 printf("MidPrioThread is running.\n");
55 osDelay(THREAD_DELAY_1S);
56 }
57 }
58
LowPrioThread(void)59 void LowPrioThread(void)
60 {
61 while (1) {
62 osMutexAcquire(g_mutexId, osWaitForever);
63 printf("LowPrioThread is running.\n");
64
65 // block mutex for 3s
66 osDelay(THREAD_DELAY_3S);
67 osMutexRelease(g_mutexId);
68 }
69 }
70
71 /**
72 * @brief Main Entry of the Mutex Example
73 *
74 */
MutexExample(void)75 void MutexExample(void)
76 {
77 osThreadAttr_t attr;
78
79 attr.attr_bits = 0U;
80 attr.cb_mem = NULL;
81 attr.cb_size = 0U;
82 attr.stack_mem = NULL;
83 attr.stack_size = THREAD_STACK_SIZE;
84
85 attr.name = "HighPrioThread";
86 attr.priority = HIGH_THREAD_PRIO;
87 if (osThreadNew((osThreadFunc_t)HighPrioThread, NULL, &attr) == NULL) {
88 printf("Failed to create HighPrioThread!\n");
89 }
90
91 attr.name = "MidPrioThread";
92 attr.priority = MID_THREAD_PRIO;
93 if (osThreadNew((osThreadFunc_t)MidPrioThread, NULL, &attr) == NULL) {
94 printf("Failed to create MidPrioThread!\n");
95 }
96
97 attr.name = "LowPrioThread";
98 attr.priority = LOW_THREAD_PRIO;
99 if (osThreadNew((osThreadFunc_t)LowPrioThread, NULL, &attr) == NULL) {
100 printf("Failed to create LowPrioThread!\n");
101 }
102
103 g_mutexId = osMutexNew(NULL);
104 if (g_mutexId == NULL) {
105 printf("Failed to create Mutex!\n");
106 }
107 }
108 APP_FEATURE_INIT(MutexExample);
109