README_zh.md
1# Niobe407开发板OpenHarmony内核编程开发——Thread多线程
2本示例将演示如何在Niobe407开发板上使用cmsis 2.0 接口进行多线程开发
3
4## Thread API分析
5
6## osThreadNew()
7
8```c
9osThreadId_t osThreadNew(osThreadFunc_t func, void *argument,const osThreadAttr_t *attr )
10```
11**描述:**
12
13函数osThreadNew通过将线程添加到活动线程列表并将其设置为就绪状态来启动线程函数。线程函数的参数使用参数指针*argument传递。当创建的thread函数的优先级高于当前运行的线程时,创建的thread函数立即启动并成为新的运行线程。线程属性是用参数指针attr定义的。属性包括线程优先级、堆栈大小或内存分配的设置。可以在RTOS启动(调用 osKernelStart)之前安全地调用该函数,但不能在内核初始化 (调用 osKernelInitialize)之前调用该函数。
14> **注意** :不能在中断服务调用该函数
15
16
17**参数:**
18
19|名字|描述|
20|:--|:------|
21| func | 线程函数. |
22| argument |作为启动参数传递给线程函数的指针|
23| attr |线程属性|
24
25## 软件设计
26
27**主要代码分析**
28
29在OS_Thread_example函数中,通过osThreadNew()函数创建了thread1和thread2两个进程,thread1和thread2启动后会输出打印日志。
30
31```c
32void thread_entry1(void)
33{
34 int sum=0;
35 while (1)
36 {
37 /* 示例代码 */
38 printf("This is Niobe407 Thread1----%d\r\n",sum++);
39 usleep(500000);
40 }
41}
42
43void thread_entry2(void)
44{
45 int sum=0;
46 while (1)
47 {
48 /* 示例代码 */
49 printf("This is Niobe407 Thread2----%d\r\n",sum++);
50 usleep(500000);
51 }
52}
53
54static void OS_Thread_example(void)
55{
56 osThreadAttr_t attr;
57
58 attr.name = "thread1";
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 attr.priority = 25;
65
66 if (osThreadNew((osThreadFunc_t)thread_entry1, NULL, &attr) == NULL) {
67 printf("Failed to create thread1!\n");
68 }
69
70 attr.name = "thread2";
71
72 if (osThreadNew((osThreadFunc_t)thread_entry2, NULL, &attr) == NULL) {
73 printf("Failed to create thread2!\n");
74 }
75}
76
77```
78
79## 编译调试
80- 进入//kernel/liteos_m目录, 在menuconfig配置中进入如下选项:
81
82 `(Top) → Platform → Board Selection → select board niobe407 → use talkweb niobe407 application → niobe407 application choose`
83
84- 选择 `002_system_thread`
85
86- 回到sdk根目录,执行`hb build -f`脚本进行编译。
87
88### 运行结果
89
90示例代码编译烧录代码后,按下开发板的RESET按键,通过串口助手查看日志,Thread1和Thread2会交替打印信息
91```
92This is Niobe407 Thread1----0
93This is Niobe407 Thread2----0
94This is Niobe407 Thread1----1
95This is Niobe407 Thread2----1
96This is Niobe407 Thread1----2
97This is Niobe407 Thread2----2
98This is Niobe407 Thread1----3
99This is Niobe407 Thread2----3
100This is Niobe407 Thread1----4
101This is Niobe407 Thread2----4
102This is Niobe407 Thread1----5
103This is Niobe407 Thread2----5
104```
105