micropython / micropython/micropython
rp2: micropython.schedule() thread safety
Nobody has claimed this yet.
- Dominant language
- C
- Stars
- 22.1k
- Forks
- 9k
- Avg merge
- 6d 4h
- Merged PRs (30d)
- 16
Description
The canonical use for micropython.schedule() is to enable a hard ISR to schedule a "soft" ISR which has GIL protection. For this to occur the "soft" code must run on the same core (0) as the main program.
In the following script the main program and the hard ISR run on core 0 while soft_isr runs on core 1. If soft_isr were to access shared data there would be a risk of corruption, for example if it accessed a global while the globals dict was being re-hashed.
The problem is that user code is running on another core under circumstances in which this would not be expected.
import micropython
import _thread
import time
from machine import Pin, mem32
pout = Pin(16, Pin.OUT) # Link these pins
ipin = Pin(17, Pin.IN)
def pcore(s):
print(f'{s} CPU core: {mem32[0xd0000000]} thread: {_thread.get_ident()}')
def isr(_):
print(mem32[0xd0000000])
micropython.schedule(soft_isr, None)
ipin.irq(handler=isr, hard=True)
def soft_isr(_): # Scheduled by hard ISR
pcore('soft')
def busy():
while True:
time.sleep(1)
pcore('thread')
_thread.start_new_thread(busy, ())
pcore('main')
while True:
pout(not pout())
time.sleep_ms(200)
Outcome:
<irq>
main CPU core: 0 thread: 537095120
0
soft CPU core: 1 thread: 536912624
0
soft CPU core: 1 thread: 536912624
0
soft CPU core: 1 thread: 536912624
0
soft CPU core: 1 thread: 536912624
0
soft CPU core: 1 thread: 536912624
thread CPU core: 1 thread: 536912624
0
soft CPU core: 1 thread: 536912624
0
This arose from discussion https://github.com/micropython/micropython/discussions/10638
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 with the micropython.schedule() entry point and the RP2 _thread behavior described in the issue, then run the supplied reproduction script on the affected hardware. Done would require an agreed correction so scheduled soft ISR code runs with the expected core and thread-safety guarantees, plus verification that shared-data access no longer has the reported risk.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- c, python
- Domain
- embedded-iot
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100