README.md
1# BearPi-HM_Nano开发板OpenHarmony内核编程开发——Thread多线程
2本示例将演示如何在BearPi-HM_Nano开发板上使用cmsis 2.0 接口进行多线程开发。
3
4
5## Thread API分析
6
7### osThreadNew()
8
9```c
10osThreadId_t osThreadNew(osThreadFunc_t func, void *argument,const osThreadAttr_t *attr )
11```
12**描述:**
13
14函数osThreadNew通过将线程添加到活动线程列表并将其设置为就绪状态来启动线程函数。线程函数的参数使用参数指针*argument传递。当创建的thread函数的优先级高于当前运行的线程时,创建的thread函数立即启动并成为新的运行线程。线程属性是用参数指针attr定义的。属性包括线程优先级、堆栈大小或内存分配的设置。可以在RTOS启动(调用 osKernelStart)之前安全地调用该函数,但不能在内核初始化 (调用 osKernelInitialize)之前调用该函数。
15> **注意** :不能在中断服务调用该函数。
16
17
18**参数:**
19
20|参数名|描述|
21|:--|:------|
22| func | 线程函数。 |
23| argument |作为启动参数传递给线程函数的指针。|
24| attr |线程属性。|
25
26## 软件设计
27
28**主要代码分析**
29
30在ThreadExample函数中,通过osThreadNew()函数创建了Thread1和Thread2两个进程,Thread1和Thread2启动后会输出打印日志。
31
32```c
33/**
34 * @brief Thread1 entry
35 *
36 */
37void Thread1(void)
38{
39 int sum = 0;
40
41 while (1) {
42 printf("This is BearPi-HM_Nano Thread1----%d\n", sum++);
43 usleep(THREAD_DELAY_1S);
44 }
45}
46
47/**
48 * @brief Thread2 entry
49 *
50 */
51void Thread2(void)
52{
53 int sum = 0;
54
55 while (1) {
56 printf("This is BearPi-HM_Nano Thread2----%d\n", sum++);
57 usleep(THREAD_DELAY_500MS);
58 }
59}
60
61/**
62 * @brief Main Entry of the Thread Example
63 *
64 */
65static void ThreadExample(void)
66{
67 osThreadAttr_t attr;
68
69 attr.name = "Thread1";
70 attr.attr_bits = 0U;
71 attr.cb_mem = NULL;
72 attr.cb_size = 0U;
73 attr.stack_mem = NULL;
74 attr.stack_size = THREAD_STACK_SIZE;
75 attr.priority = THREAD_PRIO;
76
77 // Create the Thread1 task
78 if (osThreadNew((osThreadFunc_t)Thread1, NULL, &attr) == NULL) {
79 printf("Failed to create Thread1!\n");
80 }
81
82 // Create the Thread2 task
83 attr.name = "Thread2";
84 if (osThreadNew((osThreadFunc_t)Thread2, NULL, &attr) == NULL) {
85 printf("Failed to create Thread2!\n");
86 }
87}
88
89```
90
91## 编译调试
92
93### 修改 BUILD.gn 文件
94
95修改 `device\bearpi\bearpi_hm_nano\app`路径下 BUILD.gn 文件,指定 `thread_example` 参与编译。
96
97```r
98"A1_kernal_thread:thread_example",
99#"A2_kernel_timer:timer_example",
100#"A3_kernel_event:event_example",
101#"A4_kernel_mutex:mutex_example",
102#"A5_kernel_semaphore:semaphore_example",
103#"A6_kernel_message:message_example",
104```
105
106
107
108### 运行结果
109
110示例代码编译烧录代码后,按下开发板的RESET按键,通过串口助手查看日志,Thread1和Thread2会交替打印信息。
111```c
112This is BearPi-HM_Nano Thread1----2
113This is BearPi-HM_Nano Thread2----4
114This is BearPi-HM_Nano Thread2----5
115This is BearPi-HM_Nano Thread1----3
116This is BearPi-HM_Nano Thread2----6
117This is BearPi-HM_Nano Thread2----7
118```
119