• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2022 Talkweb 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 "ohos_run.h"
21 #include "cmsis_os2.h"
22 
23 osMutexId_t mutex_id;
24 
firstThread(void)25 void firstThread(void)
26 {
27     osDelay(100U);
28     while (1) {
29         osMutexAcquire(mutex_id, osWaitForever);
30         printf("firstThread is Acquire.\r\n");
31         osDelay(1000U);
32         osMutexRelease(mutex_id);
33     }
34 }
35 
twoThread(void)36 void twoThread(void)
37 {
38     osDelay(1000U);
39     while (1) {
40         printf("twoThread is Acquire.\r\n");
41         osDelay(1000U);
42     }
43 }
44 
threeThread(void)45 void threeThread(void)
46 {
47     while (1) {
48         osMutexAcquire(mutex_id, osWaitForever);
49         printf("threeThread is Acquire.\r\n");
50         osDelay(3000U);
51         osMutexRelease(mutex_id);
52     }
53 }
54 
os_mutex_example(void)55 void os_mutex_example(void)
56 {
57     osThreadAttr_t attr;
58 
59     attr.attr_bits = 0U;
60     attr.cb_mem = NULL;
61     attr.cb_size = 0U;
62     attr.stack_mem = NULL;
63     attr.stack_size = 1024 * 4;
64 
65     attr.name = "firstThread";
66     attr.priority = 26;
67     if (osThreadNew((osThreadFunc_t)firstThread, NULL, &attr) == NULL) {
68         printf("create firstThread failed!\n");
69     }
70 
71     attr.name = "twoThread";
72     attr.priority = 25;
73     if (osThreadNew((osThreadFunc_t)twoThread, NULL, &attr) == NULL) {
74         printf("create twoThread failed!\n");
75     }
76 
77     attr.name = "threeThread";
78     attr.priority = 24;
79     if (osThreadNew((osThreadFunc_t)threeThread, NULL, &attr) == NULL) {
80         printf("create threeThread failed!\n");
81     }
82 
83     mutex_id = osMutexNew(NULL);
84     if (mutex_id == NULL) {
85         printf("create Mutex failed!\n");
86     }
87 }
88 
89 OHOS_APP_RUN(os_mutex_example);
90