RT-thread線程創建:動態線程與靜態線程


本文介紹了如何創建一個動態線程和一個靜態線程

RT-thread版本:RT-thread system 3.1.0

開發環境:MDK5

為了編程方便,創建了sample1.c文件,然后添加到工程中

話不多說,先上代碼

#include "rtthread.h"


#define stack_size 1024   //設置動態線程棧大小
#define priority 25    //設置優先級
#define tick 10       //時間片


static rt_thread_t tid1 = NULL;  //指針初始化為NULL

static void thread1_entry(void *parameter)   //線程1入口函數
{
    rt_base_t i;
    rt_uint16_t count = 0;
    for(i = 0; i < 10; i++)
    {
        rt_kprintf("thread1, count: %d\n", count++);
        
    }
    
}

ALIGN(RT_ALIGN_SIZE);

static struct rt_thread thread2;

static char thread_stack[1024];


static void thread2_entry(void *parameter)   //線程2入口代碼
{
    rt_base_t i, count = 0;
    for(i = 0; i < 10; i++)
    {
        rt_kprintf("thread2, count: %d\n", count++);
        
    }
    rt_kprintf("thread2 exit!\n");
    
}

void sample1(void *parameter)        //線程創建函數
{
    tid1 = rt_thread_create("thread1", 
                            thread1_entry,
                            RT_NULL, 
                                                stack_size, priority, tick
                                                    );
    if(tid1 != NULL)
        rt_thread_startup(tid1);
  rt_thread_init(&thread2, "thread2", thread2_entry, RT_NULL, &thread_stack[0], sizeof(thread_stack), priority-1, tick);
        rt_thread_startup(&thread2);
    
}
MSH_CMD_EXPORT(sample1, RT-Thread first sample); //添加到msh命令列表中

在sample1.c中添加上述代碼,點擊按鈕進行仿真,在串口框中輸入“sample1”,即可看到效果如下圖。

 

線程2輸出“thread2 exit!”后被系統自動刪除,線程1開始執行。

對於能夠執行結束的線程,系統在執行結束后,自動刪除。

學習RT-thread推薦書籍:嵌入式實時操作系統RT-Thread設計與實現,還是很不錯的。

RT-thread官網也有視頻教程,視頻可以看完書再看,容易接受一點。

 

 

                            


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM