How to make server threads in Python?

Asked

Viewed 352 times

0

Hello I’m a beginner in Python and I’m creating a simple server but I can’t create independent threads. When the client connects to the server it calls the worker function that waits for a client message to send a response. It turns out that only one connection is executed at a time and in the order of connection, leaving the other customers who already sent the message waiting.

while True:
    conn, address = ss.accept()
    print('DEBUG: Connected by ',  address)
    obj = threading.Thread(target = ServerWorker.worker(conn))
    obj.start()

Worker function:

def worker(conn):
    print('Running...')
    _in = conn.recv(1024)
    msg = _in.decode(encoding = 'utf-8')
    print('DEBUG: Processing ', msg, '...')
    msg = 'ECHO: ' + msg
    _out = conn.sendall(bytes(msg,encoding = 'utf-8'))
    conn.close()

I just tried calling another script . py instead of the thread but I couldn’t pass the Conn object as argument. Please help me.

1 answer

0


The way you’re doing, it’s calling the function ServerWorker.worker() first and then trying to start the thread with the result of this function (which in this case is None since it does not return anything). Parentheses force the function call to be extracted before starting the thread. Your current code is equivalent to this:

resultado = ServerWorker.worker(conn)
obj = threading.Thread(target = resultado)

In fact, who will call the function is the module threading python and not your code. You must pass the function without calling it yourself, ie do not put the parentheses () after the function name, thus passing the function itself and not the result of it.

The parameters you want to pass to the function target must be passed in args and kwargs, so that the module threading can then pass them on to their function when the time comes, as it says in documentation:

obj = threading.Thread(target=ServerWorker.worker, args=[conn])

See that an iterable should be passed with the positional parameters, in the example above was the list [].

  • I got it. The thread really wasn’t created until the function ran. Thank you very much!

  • @Good that Wandersonlima helped! if my answer answered, consider marking it as accepted, to close the question.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.