← index #12698Issue #10621
Duplicate · high · value 4.389
QUERY · ISSUE

RP2: Global variable lost/distorted after start_new_thread() with try/except

openby rkompassopened 2023-10-15updated 2023-10-16
bug
import _thread
from time import sleep_ms

a = b = 1          # these have to be 2 variables, for the bug to occur
def test():
    global a
    try:           # the try / except block has to be there too
        a = 2
    except Exception as e:
        print(e)

_thread.start_new_thread(test,())
c = 5              # and also this variable has to be here, before the sleep_ms()

sleep_ms(10)
print("a is "+str(a))

reports
a is 1 which should be a is 2.

@pdg137 found even that a is __main__may be reported in a similar setup, with MicroPython v1.21.0 on 2023-10-06 or older.

This issue is a reincarnation of https://github.com/micropython/micropython/issues/10621 in a more minimal setting (thanks to @pdg137), so hopefully it will be easier to trace the bug.

Maintainers: If it was the wrong policy to raise a new issue, please give a short feedback, then I may delete this one and rename https://github.com/micropython/micropython/issues/10621.

CANDIDATE · ISSUE

RP2: global variable lost at maximum recursion depth in second thread

openby rkompassopened 2023-01-29updated 2023-10-15
bug

A global variable reportedly is not there (NameError: name 'a' isn't defined) although it should be there.
This occurs in a setting of a recursion test function that hits the limit of 19 recursions on the second thread/core on a RPi2040.
The global variable, a, is updated in this function.
Strangely this only occurs if also two other global variables are defined, sleep_ms is imported as a single import and the maximum recursion depth exception is catched with try/except.
The code is as follows:

import _thread
from time import sleep_ms #, sleep_us  # if more than one functions imported there is no NameError

a = 0
b = 0

def recursionTest():
    global a
    a += 1
    try:
        recursionTest()
    except Exception as errorMsg:
        print(errorMsg)

_thread.start_new_thread(recursionTest,())

c = 0
sleep_ms(10)
print('recursion depth:', a)

The output is as follows:

Unhandled exception in thread started by <function recursionTest at 0x20008d50>
Traceback (most recent call last):
  File "<stdin>", line 9, in recursionTest
NameError: name 'a' isn't defined
recursion depth: 0

If c = 0, for example is commented out the output changes to (correct);

maximum recursion depth exceeded
recursion depth: 19

This was on `MicroPython v1.19.1 on 2022-07-27; Raspberry Pi Pico with RP2040

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied