源代码github网址:
https://github.com/skawu/RT-Thread-STM32F103ZET6,在分支idcard中。
直接贴代码:
创建一个文件,内容如下:
#include <stm32f10x.h> #include "thread_test.h" #include <rtthread.h> #include <rthw.h> /* 一、动态线程 初始化两个动态线程,它们拥有相同的入口函数,相同的优先级 但是它们的入口参数不同 二、任务间同步与通信 关闭中断进行全局变量的访问,关闭中断会导致整个系统不能响应外部中断, 所以需保证关闭中断的时间非常短。 */ #define THREAD_PRIORITY 25 #define THREAD_STACK_SIZE 512 #define THREAD_TIMESLICE 5 /* 定义静态全局变量 */ static rt_uint32_t count = 1; /* 指向线程控制块的指针 */ static rt_thread_t tid1 = RT_NULL; static rt_thread_t tid2 = RT_NULL; /* 静态全局变量操作函数 */ //待添加 /* 线程入口 */ //rt_uint32_t count = 0; //串口看上去是同时打印tid1和tid2的数值后延时1s,而不是tid1延时1s,tid2延时1s,此问题待考虑解决办法 static void thread_entry(void *parameter) { rt_base_t level; rt_uint32_t no = (rt_uint32_t) parameter; //获取线程的入口参数 while (1) { //关闭中断 level = rt_hw_interrupt_disable(); count += no; //恢复中断 rt_hw_interrupt_enable(level); //打印线程计数值输出 rt_kprintf("thread%d count: %d\n", no, count); //休眠100个OS Tick rt_thread_delay(100); } } /* 用户层调用创建线程 */ int app_init_thread_test(void) { //创建线程1 tid1 = rt_thread_create("thread1", thread_entry, (void *)1, THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE); if (tid1 != RT_NULL) { rt_thread_startup(tid1); } else { return -1; } //创建线程2 tid2 = rt_thread_create("thread2", thread_entry, (void *)2, THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE); if (tid2 != RT_NULL) { rt_thread_startup(tid2); } else { return -1; } return 0; }
在rt_application_init函数中添加第20行的代码:
1 int rt_application_init(void) 2 { 3 rt_thread_t init_thread; 4 rt_err_t result; 5 /* init led thread */ 6 result = rt_thread_init(&led_thread, 7 "led", 8 led_thread_entry, 9 RT_NULL, 10 (rt_uint8_t *)&led_stack[0], 11 sizeof(led_stack), 12 20, 13 5); 14 15 if (result == RT_EOK) 16 { 17 rt_thread_startup(&led_thread); 18 } 19 20 if (-1 == app_init_thread_test()) 21 { 22 return -1; 23 } 24 25 #if (RT_THREAD_PRIORITY_MAX == 32) 26 init_thread = rt_thread_create("init", 27 rt_init_thread_entry, RT_NULL, 28 2048, 8, 20); 29 #else 30 init_thread = rt_thread_create("init", 31 rt_init_thread_entry, RT_NULL, 32 2048, 80, 20); 33 #endif 34 35 if (init_thread != RT_NULL) 36 { rt_thread_startup(init_thread); } 37 38 return 0; 39 }
执行效果: