问题
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