简体   繁体   English

Python代码在线程启动后不继续执行

[英]Python code not continuing execution after thread started

I am writing a threaded Python script for the first time and running into some trouble. 我是第一次编写一个线程Python脚本并遇到麻烦。 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. 一般的想法是Raspberry Pi从蓝牙连接接收数据,然后该数据用于创建调用start_laps方法的线程。 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()

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. 执行函数start_laps ,这显然会阻止程序。 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 这将使用给定的args在创建的Thread执行该函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM