← index #12698Issue #2916
Related · medium · value 0.608
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

NameError: name 'i' is not defined when using threads

closedby crasuopened 2017-02-26updated 2017-03-06

Hi,

I am playing around with the _thread module. I am having the problem that some variables are suddenly vanishing.

import _thread
import utime

i=0
def run():
    global i
    while True:
        i = (i + 1) % 100
    print("terminating")

def start():
    _thread.start_new_thread(run, ())
    print("sleeping")
    utime.sleep(3)
    print("wakeup")

When I run this I get:

>>> bug.start()
sleeping
wakeup
>>> Unhandled exception in thread started by <function run at 0x3ffe2740>
Traceback (most recent call last):
  File "bug.py", line 8, in run
NameError: name 'i' is not defined

Is this expected? Seems surprising to me.

I am using micropython 1.8.7 on the wipy 2.0.

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