RTT例程練習 2 7 郵箱 mailbox

2021-06-13 03:41:21 字數 2697 閱讀 3396

郵箱是作業系統中,乙個程序給另乙個程序傳送訊息的方式。在裸奔的微控制器中,在兩個函式中交換資訊的時候,我們通常選擇最簡便的方式-全域性變數,這種程式設計模式無疑是降低了安全性和可靠性。再且,郵箱還能起到掛起執行緒的作用。

本實驗中建立乙個郵箱,兩個執行緒,執行緒2以一定週期傳送郵箱,執行緒1以一定週期從郵箱中取出郵件。當執行緒2中傳送20封郵件之後,傳送一封特殊的郵件通知其他執行緒,自己已經執行結束。執行緒1取出郵件後,檢查郵件是否是特殊郵件,如果是,則執行緒1也退出。

程式:

#include void rt_init_thread_entry(void *parameter)

static struct rt_mailbox mb;

static rt_uint8_t mb_pool[128];

static rt_uint8_t mb_str1 = "i'm a mail!";

static rt_uint8_t mb_str2 = "this is another mail!";

static rt_uint8_t mb_str3 = "over!";

static rt_uint8_t thread1_stack[1024];

struct rt_thread thread1;

static void thread1_entry(void *parameter)

}rt_mb_detach(&mb);

}static rt_uint8_t thread2_stack[1024];

struct rt_thread thread2;

static void thread2_entry(void *parameter)

else

rt_thread_delay(20);

}rt_mb_send(&mb, (rt_uint32_t)&mb_str3[0]);

}

init_thread = rt_thread_create("init",

rt_init_thread_entry, rt_null,

2048,

8, 20);

if (init_thread != rt_null)

rt_thread_startup(init_thread);

rt_thread_init(&thread1,

"thread1",

thread1_entry,

rt_null,

&thread1_stack[0],

sizeof(thread1_stack),10,5);

rt_thread_startup(&thread1);

rt_thread_init(&thread2,

"thread2",

thread2_entry,

rt_null,

&thread2_stack[0],

sizeof(thread2_stack),10,5);

rt_thread_startup(&thread2);

return 0;

}

結果

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:i'm a mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:this is another mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:i'm a mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:this is another mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:i'm a mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:this is another mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:i'm a mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:this is another mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:i'm a mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:this is another mail!

thread1: try to recv a mail

thread1: get a mail from mailbox, the content:over

RTT例程練習 1 3 執行緒讓出

rtt 支援相同優先順序,而ucosii 不支援。如果乙個執行緒不呼叫rt thread delay 來讓出排程器,那麼它就會一直執行,其它執行緒永遠處於就緒態。而相同優先順序的執行緒,在初始化或建立時還定義了其單次執行的最長的時間片,強迫其讓出排程器。這裡,使用rt thread yield 也可...

RTT例程練習 1 3 執行緒讓出

rtt 支援相同優先順序,而ucosii 不支援。如果乙個執行緒不呼叫rt thread delay 來讓出排程器,那麼它就會一直執行,其它執行緒永遠處於就緒態。而相同優先順序的執行緒,在初始化或建立時還定義了其單次執行的最長的時間片,強迫其讓出排程器。這裡,使用rt thread yield 也可...

RTT例程練習 1 1 動態執行緒建立,刪除

建立兩個動態執行緒,thread2 執行4s後刪除thread1。這裡兩個都為動態執行緒,所謂動態執行緒即在堆中動態建立,刪除之後也從ram中消失。區別於靜態執行緒。由於是動態,所以需開啟 define rt using heap include rt thread t tid1 rt null r...