我想了解为什么我必须等待接收器线程结束其工作才能执行其他操作。 我知道我的 sock_listen 函数正在等待连接,这就是它的用途,但我不明白为什么这没有发生在我的线程“内”。
抱歉,如果这是一个愚蠢的问题,但我有点迷路了! 预先感谢您!
def sock_listen(address, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (address,port)
print("Starting listener on %s and port %s" % server_address)
sock.bind(server_address)
sock.listen(1)
while True:
print("[-] Waiting for connection")
connection, client_address = sock.accept()
print("[+] Connection from " + str(client_address))
data = connection.recv(256)
while (data) :
print("[" + time.strftime("%H:%M:%S") + "] " + str(data))
data = connection.recv(256)
receiver = threading.Thread(sock_listen("localhost",10000))
print("Nothing reaches me, I can not be printed until the sock_connect func is done looping!")
receiver.start()
我的目标是创建一个 TCP 简单聊天,其中专用线程将处理和打印传入消息,主进程将发送用户输入(消息)
最佳答案
当您编写 threading.Thread(sock_listen("localhost",10000))
时,您已经在调用 sock_listen
并将此调用的结果传递到 >线程
构造函数。
您需要将可调用的 sock_listen
作为 target
和 sock_listen
的参数分别传递给 Thread
:
receiver = threading.Thread(target=sock_listen, args=("localhost",10000))
启动新线程后,您的目标函数将在新线程中被调用。
关于python - 为什么我的线程在启动之前就执行目标函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684329/