以正点原子stm32 f407板子为例子,如何创建工程 CubeMX+CubeIDE在我之前的文章里提到了,这里我就不多重复。
有关线程优先级的两个参数 priority和preemption,我们来看看在官网是如何定义的
在main.c里面添加一个printf转串口的代码,这样我们用printf就可以直接转发到串口,我在之前用CubeMX设置的是串口1,用的是PA9和PA10,所以这里也设置的是huart1
/* USER CODE BEGIN PTD */
#if defined ( __GNUC__) && !defined(__clang__)
/* With GCC, small printf (option LD Linker->Libraries->Small printf
set to 'Yes') calls __io_putchar() */
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch,1,0xFFFF);
return ch;
}
/* USER CODE END PD */
接下来我们在Core里面新建一个threadTest的文件夹,写上hey.c和hey.h两个文件
把这个文件夹添加到路径下
hey.h
#include "tx_api.h"
#include "main.h"
#include "stdio.h"
void processHey(VOID *memory_ptr);
hey.c
/*
* hey.c
*
* Created on: Jul 14, 2024
* Author: liqun
*/
#include "hey.h"
TX_THREAD Hey;
UINT OldPriority;
static VOID hey_entry(ULONG thread_input);
void processHey(VOID *memory_ptr){
TX_BYTE_POOL *byte_pool = (TX_BYTE_POOL*)memory_ptr;
CHAR *pointer;
// pointer = malloc(1024);
tx_byte_allocate(byte_pool, (VOID **) &pointer, 1024, TX_NO_WAIT);
INT ret = tx_thread_create(&Hey,"hey thread",hey_entry,0,pointer,1024,1,1,TX_NO_TIME_SLICE,TX_AUTO_START);
if(ret != TX_SUCCESS){
printf("hey is not be created\n");
}
}
static VOID hey_entry(ULONG thread_input){
printf("thread hey is starting\n");
CHAR *name;
UINT state;
ULONG run_count;
UINT priority;
UINT preemption_threshold;
UINT time_slice;
TX_THREAD *next_thread;
TX_THREAD *suspended_thread;
UINT status;
if(tx_thread_info_get(&Hey,&name,&state, &run_count,&priority, &preemption_threshold,&time_slice, &next_thread,&suspended_thread)==TX_SUCCESS){
printf("Current Hey priority is %d \n",priority);
}
else{
printf("get thread info failed\n");
}
if(tx_thread_priority_change(&Hey,10,&OldPriority)==TX_SUCCESS){
printf("thread priority is changed from 1 to 10\n");
if(tx_thread_info_get(&Hey,&name,&state, &run_count,&priority, &preemption_threshold,&time_slice, &next_thread,&suspended_thread)==TX_SUCCESS){
printf("Current Hey priority is %d \n",priority);
};
}
else{
printf("thread priority is not changed\n");
};
}
在hey.c里面,我们创建了一个线程,线程占用的栈大小为1024,指针为pointer,记得要初始化一下指针(我这里用的是threadx的方法,如果不想这么复杂,需要传入memory_ptr然后byte_pool的话,其实直接pointer = malloc(1024)也是可以运行的,就是自己要手动free)。在线程hey_enter里面,我们调用了tx_thread_info_get去获取当前线程的所有参数,然后我们用tx_thread_priority_change去修改线程的优先级。当然,如果需要修改线程的抢占,也是可以的,有tx_thread_preemption_change这个函数
然后在app_azure_rtos.c里引入hey.h头文件并调用
运行程序,打开串口调试助手