Reputation: 6098
I am writing a threaded Python script for the first time and running into some trouble. The general idea is that a Raspberry Pi receives data from a Bluetooth connection, this data is then used to create a thread that calls the start_laps
method. Once this thread is started, I need to continue listening for new data to determine if the thread should be killed. However, my code is not continuing execution after the thread is started. What would cause this?
import json
import bluetooth
import threading
import timed_LEDs
import subprocess
import ast
def start_laps(delay, lap_times):
timed_LEDs.start_LEDs(delay, lap_times)
# put pi in discoverable
subprocess.call(['sudo', 'hciconfig', 'hci0', 'piscan'])
server_socket = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = 1
server_socket.bind(("", port))
server_socket.listen(1)
client_socket, address = server_socket.accept()
print("Accepted connection from ", address)
threads = []
while True:
print("RECEIVING")
data = client_socket.recv(1024)
data = json.loads(data.decode())
print(data)
if(data["lap_times"]):
print("STARTING THREAD")
t = threading.Thread(target=start_laps(int(data["delay"]), ast.literal_eval(data["lap_times"])))
threads.append(t)
t.start()
elif data == "stop":
print("Stop dat lap")
else:
print(data)
client_socket.close()
Upvotes: 1
Views: 3264
Reputation: 7896
You are using the threading module wrong. This line
threading.Thread(target=start_laps(int(data["delay"]), ast.literal_eval(data["lap_times"])))
executes the function start_laps
, which obviously blocks the program. What you want is the following:
threading.Thread(target=start_laps, args=(int(data["delay"]), ast.literal_eval(data["lap_times"])))
This executes the function in the created Thread
with the given args
Upvotes: 4