RT-Thread / RT-Thread/rt-thread
[Bug] 多线程操作rt_device_open和rt_device_close同一个设备,可能会使ref_count错误变化
Open
Nobody has claimed this yet.
- Dominant language
- C
- Stars
- 12.2k
- Forks
- 5.4k
- Avg merge
- 4d 12h
- Merged PRs (30d)
- 40
Description
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
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reading the implementations of rt_device_open and rt_device_close, focusing on the ref_count updates and the RT_ASSERT condition. Reproduce concurrent operations on one device if possible, then verify that ref_count remains consistent and the assertion is not triggered under the reported scenario.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c
- Domain
- embedded-iot, operating-systems
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100