@@ -1100,6 +1100,61 @@ PyWorker("worker.py", type="micropython")
11001100< div id= " output" >< / div> <!-- The display target -->
11011101` ` `
11021102
1103+ !!! info
1104+
1105+ Sometimes code running on a worker gets stuck in an infinite loop and
1106+ becomes unresponsive. There are many complicated reasons why this might
1107+ happen, but when it does happen you likely want to break out of this
1108+ loop. This is where the ` isStuck` and ` notStuck` features come into play.
1109+
1110+ If you have code in the worker that could end up in an unresponsive
1111+ infinite loop, for example:
1112+
1113+ ` ` ` python
1114+ import time
1115+
1116+ while True:
1117+ time .sleep (1 )
1118+ print (" Stuck in a loop" )
1119+ ` ` `
1120+
1121+ ...then you only need wrap this code in the worker like this:
1122+
1123+ ` ` ` python
1124+ import time
1125+ from pyscript import sync
1126+ is_stuck = sync .isStuck
1127+ break_loop = sync .notStuck
1128+
1129+ def is_not_stuck (condition):
1130+ if is_stuck ():
1131+ # this is a must to reset the " stuck" state
1132+ break_loop ()
1133+ # throw an error to get out of the loop
1134+ raise RuntimeError (' Worker was stuck, but now it is unstuck' )
1135+ return condition
1136+
1137+ while is_not_stuck (True):
1138+ time .sleep (1 )
1139+ print (" Stuck in a loop" )
1140+ ` ` `
1141+
1142+ From your code on the main thread you may have something like this:
1143+
1144+ ` ` ` python
1145+ from pyscript import PyWorker
1146+
1147+ w = PyWorker (" sticky_code.py" , type= " micropython" )
1148+
1149+ @when (" click" , " unstick_button" )
1150+ def handle_unstick ():
1151+ w .unstuck ()
1152+ ` ` `
1153+
1154+ This starts the worker with you code that could get into an infinite loop,
1155+ then defines a function that calls the ` unstuck ()` function on the worker
1156+ when a button on the UI is clicked.
1157+
11031158### ` pyscript .workers `
11041159
11051160The ` pyscript .workers ` reference allows Python code in the main thread to
0 commit comments