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

妖精的绣舞 提交于 2019-12-24 06:38:08

问题


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

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)


回答1:


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.

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.



来源:https://stackoverflow.com/questions/53684329/why-is-my-thread-executing-the-target-function-before-i-start-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!