为什么我的线程在启动之前执行目标函数?

Why is my thread executing the target function before I start it?

我想了解为什么我必须等待我的接收器线程结束它的工作才能做任何其他事情。 我知道我的 sock_listen 函数正在等待连接,这就是它的意思,但我不明白为什么这没有发生 "within" 我的线程。

抱歉,如果这是一个愚蠢的问题,但我有点迷路了! 提前致谢!

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

我的 objective 是进行 TCP 简单聊天,其中专用线程将处理和打印传入消息,主进程将发送用户输入(消息)

当您编写 threading.Thread(sock_listen("localhost",10000)) 时,您已经在调用 sock_listen 并将此调用的结果传递给 Thread 构造函数。

您需要将可调用 sock_listen 作为 targetsock_listen 的参数分别传递给 Thread:

receiver = threading.Thread(target=sock_listen, args=("localhost",10000))

您的目标函数将在您启动后在新线程中调用。