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

标签 python multithreading python-multithreading

我想了解为什么我必须等待接收器线程结束其工作才能执行其他操作。 我知道我的 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 作为 targetsock_listen 的参数分别传递给 Thread:

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

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

关于python - 为什么我的线程在启动之前就执行目标函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53684329/

相关文章:

python - 创建一个线程安全的队列平衡器

python - 为什么我的 Python 应用程序停滞在 'system'/内核 CPU 时间

python - 如何通过 Django Rest Framework 公开 Django-Constance 设置?

python - 如何从 pandas DataFrame 生成结果列表

python - 在绘图中标记特殊的日子

java - 为什么java中线程通信不起作用?

python - 当 threading.active_count() 返回 1 时,我可以假设我的线程已完成吗?

python - f 字符串不支持行连接吗?

C# 使用 AutoResetEvent 等待来自另一个线程的输入

delphi - 检测过时的互斥体