|
前面已經(jīng)正式介紹了如何建立一個(gè)帶有RTOS的工程,那么現(xiàn)在開(kāi)始探究一下,如何在使用了RTOS的程序中建立線程。
經(jīng)過(guò)查閱,發(fā)現(xiàn)想要?jiǎng)?chuàng)建一個(gè)線程的話,那么只要調(diào)用創(chuàng)建線程的函數(shù)就可以了。一下就是其 原型。
/// 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);
從上很容易的看出,想要?jiǎng)?chuàng)建線程,首先需要準(zhǔn)備一個(gè)線程的結(jié)構(gòu)體,和進(jìn)入線程的時(shí)候的參數(shù)。
這里我們首先準(zhǔn)備兩個(gè) 結(jié)構(gòu)體,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 所指的就是 線程的入口地址
當(dāng)準(zhǔn)備好 兩個(gè) 結(jié)構(gòu)體之后,我們就可以 利用 osThreadCreate 來(lái)創(chuàng)建相應(yīng)的線程了。
我們?cè)诰程1的入口函數(shù)中 寫led1的閃光燈,線程2的入口函數(shù)中寫led2的閃光燈。來(lái)觀察相應(yīng)的實(shí)驗(yàn)現(xiàn)象。
其完整的代碼如下。
#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);
}
|
|