RP2: Global variable lost/distorted after start_new_thread() with try/except
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.
NameError: name 'i' is not defined when using threads
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.