Skip to content

[Bug] 多线程操作rt_device_open和rt_device_close同一个设备,可能会使ref_count错误变化 #11234

@shbao

Description

@shbao

RT-Thread Version

master

Hardware Type/Architectures

Cortex-M4

Develop Toolchain

IAR

Describe the bug

rt_err_t rt_device_open(rt_device_t dev, rt_uint16_t oflag)
{
    ...
    /* set open flag */
    if (result == RT_EOK || result == -RT_ENOSYS)
    {
        dev->open_flag |= RT_DEVICE_OFLAG_OPEN;

        dev->ref_count++;
        /* don't let bad things happen silently. If you are bitten by this assert,
        * please set the ref_count to a bigger type. */
        RT_ASSERT(dev->ref_count != 0);
    }

    return result;
}
rt_err_t rt_device_close(rt_device_t dev)
{
    ...

    if (dev->ref_count == 0)
        return -RT_ERROR;

    dev->ref_count--;

    if (dev->ref_count != 0)
        return RT_EOK;
    ...
    return result;
}

从rt_device_open和rt_device_close源码来看,对ref_count++和--是非原子操作,在多线程操作同一个设备时ref_count可能会不按预期变化。
实际在使用过程中,在open时有概率会进入RT_ASSERT(dev->ref_count != 0);

Other additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions