skawu RT-Thread 学习笔记(二)---线程创建及任务间通信之中断锁

源代码github网址:https://github.com/skawu/RT-Thread-STM32F103ZET6,在分支idcard中。

直接贴代码:

创建一个文件,内容如下:

#include 
#include "thread_test.h"
#include 
#include 

/*
    一、动态线程

    初始化两个动态线程,它们拥有相同的入口函数,相同的优先级
    但是它们的入口参数不同

    二、任务间同步与通信
    
    关闭中断进行全局变量的访问,关闭中断会导致整个系统不能响应外部中断,
    所以需保证关闭中断的时间非常短。
*/
#define THREAD_PRIORITY     25
#define THREAD_STACK_SIZE   512
#define THREAD_TIMESLICE    5

/* 定义静态全局变量 */
static rt_uint32_t count = 1;

/* 指向线程控制块的指针 */
static rt_thread_t tid1 = RT_NULL;
static rt_thread_t tid2 = RT_NULL;

/* 静态全局变量操作函数 */
//待添加

/* 线程入口 */
//rt_uint32_t count = 0;        //串口看上去是同时打印tid1和tid2的数值后延时1s,而不是tid1延时1s,tid2延时1s,此问题待考虑解决办法
static void thread_entry(void *parameter)
{
    rt_base_t level;
    rt_uint32_t no = (rt_uint32_t) parameter;   //获取线程的入口参数

    while (1)
    {
        //关闭中断
        level = rt_hw_interrupt_disable();
        count += no;
        //恢复中断
        rt_hw_interrupt_enable(level);
        //打印线程计数值输出
        rt_kprintf("thread%d count: %d\n", no, count);
        //休眠100个OS Tick
        rt_thread_delay(100);
    }
}

/* 用户层调用创建线程 */
int app_init_thread_test(void)
{
    //创建线程1
    tid1 = rt_thread_create("thread1", thread_entry, (void *)1, THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);

    if (tid1 != RT_NULL)
    {
        rt_thread_startup(tid1);
    }
    else
    {
        return -1;
    }

    //创建线程2
    tid2 = rt_thread_create("thread2", thread_entry, (void *)2, THREAD_STACK_SIZE, THREAD_PRIORITY, THREAD_TIMESLICE);

    if (tid2 != RT_NULL)
    {
        rt_thread_startup(tid2);
    }
    else
    {
        return -1;
    }

    return 0;
}

在rt_application_init函数中添加第20行的代码:

int rt_application_init(void)
{
    rt_thread_t init_thread;
    rt_err_t result;
    /* init led thread */
    result = rt_thread_init(&led_thread,
                            "led",
                            led_thread_entry,
                            RT_NULL,
                            (rt_uint8_t *)&led_stack[0],
                            sizeof(led_stack),
                            20,
                            5);

    if (result == RT_EOK)
    {
        rt_thread_startup(&led_thread);
    }

    if (-1 == app_init_thread_test())
    {
        return -1;
    }

#if (RT_THREAD_PRIORITY_MAX == 32)
    init_thread = rt_thread_create("init",
                                   rt_init_thread_entry, RT_NULL,
                                   2048, 8, 20);
#else
    init_thread = rt_thread_create("init",
                                   rt_init_thread_entry, RT_NULL,
                                   2048, 80, 20);
#endif

    if (init_thread != RT_NULL)
    { rt_thread_startup(init_thread); }

    return 0;
}

 

执行效果:

skawu RT-Thread 学习笔记(二)---线程创建及任务间通信之中断锁_第1张图片

 

风吹落了树叶......那就吹吧!!!

你可能感兴趣的:(RTT)