RT-thread 筆記(一)

#include <rthw.h>
#include <rtthread.h>

#define THREAD_PRIORITY      20
#define THREAD_STACK_SIZE    512
#define THREAD_TIMESLICE     5

/* 同時訪問的全局變量 */
static rt_uint32_t cnt = 0;
void thread_entry(void *parameter)
{
    rt_uint32_t no;
    rt_uint32_t level;

    no = (rt_uint32_t) parameter;
    while (1)
    {

        /*調度上鎖*/
        if(cnt < 10)
        rt_enter_critical();
        cnt += no;
        
        if(cnt = 40)
        /*調度解鎖*/
        rt_exit_critical();
        rt_kprintf("protect thread[%d]'s counter is %d\n", no, cnt);
        rt_thread_mdelay(no * 10);
    }
}

/* 用戶應用程序入口 */
int interrupt_sample(void)
{
    rt_thread_t thread;

    /* 創建t1線程 */
    thread = rt_thread_create("thread1", thread_entry, (void *)10,
                              THREAD_STACK_SIZE,
                              THREAD_PRIORITY, THREAD_TIMESLICE);
    if (thread != RT_NULL)
        rt_thread_startup(thread);


    /* 創建t2線程 */
    thread = rt_thread_create("thread2", thread_entry, (void *)20,
                              THREAD_STACK_SIZE,
                              THREAD_PRIORITY, THREAD_TIMESLICE);
    if (thread != RT_NULL)
        rt_thread_startup(thread);

    return 0;
}

/* 導出到 msh 命令列表中 */
MSH_CMD_EXPORT(interrupt_sample, interrupt sample);

此代碼是實現0–40 線程1調度,40以後線程1 、2 共同調度
但現象是
在這裏插入圖片描述

問題在於

程序設計應該嚴謹
講道理,結果應該是
10 10
10 20
10 30
10 40
20 60
10 70
10 80
20 100
。。。。

從整體上看,10的執行2次;20的執行1次
這個是沒有問題的
實際上 10 40 應該被打印的,但是退出臨界區後,線程就進行了調度,此時出cnt值爲40;
調度之後,進入20的那個線程,cnt+20 = 60接着打印60
在之後線程2主動出讓程序,由線程1執行,因爲此時cnt = 60 ,所以打印60,再然後線程1主動出讓,後面的就基本正常了
只是程序設計有問題
多線程對公共資源的保護;比如使用公共資源前打印,可能就不會出現這樣的問題。

調度關閉分層次
如果前面進去了4關閉調度,應該已經是第4層了;你就是退出一次,仍然在第3層,仍會在臨界區,不會調度,如果要實現退出
至少要保證,進去和出去的次數一樣

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章