Class variables/arguments referenced in thread task routine vs passed via thread start call? #17969
Replies: 4 comments 1 reply
-
There's a reason why it is possible to pass vars via #!micropython
# -*- coding: UTF-8 -*-
# vim:fileencoding=UTF-8:ts=4
import _thread
from time import sleep_ms
class Data:
flag = 0
def core1_good(x):
x.flag += 111 # refers to referenced ›Data‹
def core1_bad():
Data.flag += 444 # refers to global ›Data‹
def core0():
class Data:
flag = 0
gdata = globals()['Data']
#─────[ clean and tidy solution 1 local Data ]─────
_thread.start_new_thread(core1_good, (Data,))
sleep_ms(10)
print(Data, Data.flag, gdata, gdata.flag)
#─────[ clean and tidy solution 2 global Data ]─────
_thread.start_new_thread(core1_good, (globals()['Data'],))
sleep_ms(10)
print(Data, Data.flag, gdata, gdata.flag)
#─────[ ugly hack (Always refers to the global Data class) ]─────
_thread.start_new_thread(core1_bad, ())
sleep_ms(10)
print(Data, Data.flag, gdata, gdata.flag)
core0() |
Beta Was this translation helpful? Give feedback.
-
This doc provides some background on the issues around dual-core coding, e.g. the section on globals. |
Beta Was this translation helpful? Give feedback.
-
@peterhinch Thanks again. |
Beta Was this translation helpful? Give feedback.
-
@GitHubsSilverBullet, true... my question was less stylistic and more just functionality... When variables encapsulated in a class scope, I am to sure that is spaghetti code per se. But, you point is well taken. And, Peter reminded me... that given the (newer) ESP32 modules can be dual-core there is that functionality issue to deal with. Most of my ESP development has been on older ESP32 and older ESP8266 based devices, and I have walked away, for a while, ESP8266/ESP32 development, so sort of getting back into groove, hence some of the questions. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Class variables/arguments referenced in thread task routine vs passed via thread start call? Both methods work, seem functional. I find class variables referenced in thread routine a bit cleaner/clearer to understand, they come from the parent scope. Seems unless I am wrong, passing these same variables/arguments to the thread start call, is just adding to the stack overhead? This true? Or am I side ways on this? Since every python variable is by reference is there a different in overhead?
Beta Was this translation helpful? Give feedback.
All reactions