为什么我的线程在启动之前执行目标函数? [英] Why is my thread executing the target function before I start it?

查看:49
本文介绍了为什么我的线程在启动之前执行目标函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to understand why I must wait for my receiver thread to end its work before I can do anything else. I understand that my sock_listen function is awaiting a connection, that's what its meant for, but I don't understand why this isn't happening "within" my thread.

对不起,如果这是一个愚蠢的问题,但我有点迷茫!提前致谢!

Sorry if this is a stupid question but I'm kind of lost ! Thank you in advance!

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 简单聊天,其中一个专用线程将处理和打印传入的消息,而主进程将发送用户输入(消息)

My objective is to make a TCP simple chat in which a dedicated thread would handle and print incoming messages and the main process would send the user input (messages)

推荐答案

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

When you write threading.Thread(sock_listen("localhost",10000)), you are already calling sock_listen and passing the result of this call into the Thread constructor.

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

You need to pass the callable sock_listen as target and the arguments for sock_listen separately to Thread:

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

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

Your target function will then be called in the new thread after you started it.

这篇关于为什么我的线程在启动之前执行目标函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆