Python code not continuing execution after thread started

爱⌒轻易说出口 提交于 2020-08-20 06:13:33

问题


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()

回答1:


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



来源:https://stackoverflow.com/questions/49907262/python-code-not-continuing-execution-after-thread-started

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!