地址对齐
在大多数系统中需要做栈空间地址对齐,例如在 ARM 体系结构中需要向 4 字节地址对齐。
实现栈对齐的方法为,在定义栈之前,放置一条 ALIGN(RT_ALIGN_SIZE)语句,指定接下来定义的变量的地址对齐方式。其中 ALIGN 是在 rtdef.h 里面定义的一个宏,根据编译器不一样,该宏的具体定义是不一样的,在 ARM 编译器中,该宏的定义具体见代码清单 14-5。ALIGN 宏的形参 RT_ALIGB_SIZE 是在 rtconfig.h 中的一个宏,目前定义为 4。
/* 定义线程控栈时要求 RT_ALIGN_SIZE 个字节对齐 */
2 ALIGN(RT_ALIGN_SIZE)
3 /* 定义线程栈 */
4 static rt_uint8_t rt_led1_thread_stack[1024];
/* 只针对 ARM 编译器,在其它编译器,该宏的实现会不一样 */
1 #define ALIGN(n) __attribute__((aligned(n)))
静态创建线程
/* 定义线程控制块 */
static struct rt_thread led1_thread;
#include "rtdef.h"
ALIGN(RT_ALIGN_SIZE)
/* 定义线程栈 */
static rt_uint8_t rt_led1_thread_stack[1024];
/*线程函数*/
static void led1_thread_entry(void* parameter);
rt_thread_init(&led1_thread, /* 线程控制块 */
"led1", /* 线程名字 */
led1_thread_entry, /* 线程入口函数 */
RT_NULL, /* 线程入口函数参数 */
&rt_led1_thread_stack[0], /* 线程栈起始地址 */
sizeof(rt_led1_thread_stack), /* 线程栈大小 */
3, /* 线程的优先级 */
20); /* 线程时间片 */
rt_thread_startup(&led1_thread); /* 启动线程,开启调度 */
rt_err_t rt_thread_detach (rt_thread_t thread); //删除静态创建线程
动态创建线程
/*定义线程控制块*/
static rt_thread_t led1_thread = RT_NULL;
/*线程函数*/
static void led1_thread_entry(void* parameter);
led1_thread = rt_thread_create( "led1", /* 线程名字 */
led1_thread_entry, /* 线程入口函数 */
RT_NULL, /* 线程入口函数参数 */
512, /* 线程栈大小 */
3, /* 线程的优先级 */
20); /* 线程时间片 */
if (led1_thread != RT_NULL)
rt_thread_startup(led1_thread); /* 启动线程,开启调度 */
else
return -1;
rt_err_t rt_thread_delete(rt_thread_t thread); //删除动态创建线程
线程睡眠
rt_err_t rt_thread_sleep(rt_tick_t tick);
rt_err_t rt_thread_delay(rt_tick_t tick);
rt_err_t rt_thread_mdelay(rt_int32_t ms);