|
前面已经正式介绍了如何建立一个带有RTOS的工程,那么现在开始探究一下,如何在使用了RTOS的程序中建立线程。
经过查阅,发现想要创建一个线程的话,那么只要调用创建线程的函数就可以了。一下就是其 原型。
/// Create a thread and add it to Active Threads and set it tostate READY.
/// \param[in] thread_def thread definitionreferenced with \ref osThread.
/// \param[in] argument pointerthat is passed to the thread function as start argument.
/// \return thread ID for reference by other functions or NULLin case of error.
osThreadId osThreadCreate (const osThreadDef_t *thread_def,void *argument);
从上很容易的看出,想要创建线程,首先需要准备一个线程的结构体,和进入线程的时候的参数。
这里我们首先准备两个 结构体,thread1,和thread2.
osThreadDef_t thread1 = {
.pthread = thread1_function,
.tpriority = osPriorityNormal,
.instances = 1,
.stacksize = 0,
};
osThreadDef_t thread2 = {
.pthread = thread2_function,
.tpriority =osPriorityNormal,
.instances = 1,
.stacksize = 0,
};
其中 pthread 所指的就是 线程的入口地址
当准备好 两个 结构体之后,我们就可以 利用 osThreadCreate 来创建相应的线程了。
我们在线程1的入口函数中 写led1的闪光灯,线程2的入口函数中写led2的闪光灯。来观察相应的实验现象。
其完整的代码如下。
#include "stm32f10x.h"
#include
#include
void gpio_init()
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);
GPIO_InitTypeDef gpio_initStruct;
gpio_initStruct.GPIO_Mode =GPIO_Mode_Out_PP;
gpio_initStruct.GPIO_Speed =GPIO_Speed_50MHz;
gpio_initStruct.GPIO_Pin = GPIO_Pin_2;
GPIO_Init(GPIOA,&gpio_initStruct);
gpio_initStruct.GPIO_Pin =GPIO_Pin_3;
GPIO_Init(GPIOA,&gpio_initStruct);
}
void thread2_function(void const *args)
{
while(1)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_3);
osDelay(500);
GPIO_SetBits(GPIOA, GPIO_Pin_3);
osDelay(500);
}
}
osThreadDef_t thread2 = {
.pthread =thread2_function,
.tpriority = osPriorityNormal,
.instances = 1,
.stacksize = 0
};
void thread1_function(void const *args)
{
while(1)
{
GPIO_ResetBits(GPIOA,GPIO_Pin_2);
osDelay(500);
GPIO_SetBits(GPIOA, GPIO_Pin_2);
osDelay(500);
}
}
osThreadDef_t thread1 ={
.pthread =thread1_function,
.tpriority = osPriorityNormal,
.instances = 1,
.stacksize = 0,
};
int main()
{
gpio_init();
osThreadCreate((const osThreadDef_t*)&thread1, NULL);
while(1);
}
|
|