I am trying to leverage the second core of the Raspberry Pico but for some reason I cannot explain, the code hangs after few seconds. Calling the second loop directly instead of calling it with a thread on the second core works properly.
The second loop, should run 100 times but hangs at 2nd iteration. The loop gets 4000 random numbers as fast as possible, compare (I just created a small function for the sake of the example) and print the time it took to compute. Very basic.
I cannot understand what is happening there? Probably missing something very basic here, but what?
Have a lovely day,
Torpi
Code: Select all
from machine import Timer, Pin
import random
import time
import _thread
RNDBOUND = 2097152
smallWords = 0
bigWords = 0
pin = Pin(2, Pin.OUT)
def function_called_by_second_thread(word:int):
global smallWords, bigWords, RNDBOUND
if word < int(RNDBOUND / 2):
smallWords += 1
else:
bigWords += 1
def second_thread():
global smallWords, bigWords, RNDBOUND
for j in range(100):
start_time = time.ticks_ms()
for i in range(4000):
function_called_by_second_thread(random.randrange(RNDBOUND))
print(f"time to compute: {time.ticks_diff(time.ticks_ms(), start_time)}")
time.sleep_ms(500)
def toggleLED():
global pin
pin.toggle()
def main():
# Doing something on the main thread
tim = Timer(period=10, mode=Timer.PERIODIC, callback=lambda t: toggleLED())
# Doing something on the second thread (calling second_thread() directly on the main thread works properly)
_thread.start_new_thread(second_thread, ()) # This hangs after 2 iterations, why?
main()