Home > Blockchain >  Python: Threads are not running in parrallel
Python: Threads are not running in parrallel

Time:11-30

I'm trying to create a networking project using UDP connections. The server that I'm creating has to multithread in order to be able to receive multiple commands from multiple clients. However when trying to multithread the server, only one thread is running. Here is the code:

def action_assigner():
    print('Hello Assign')
    while True:
        if work_queue.qsize() != 0:
            data, client_address, request_number = work_queue.get()
            do_actions(data, client_address, request_number)


def task_putter():
    request_number = 0
    print('Hello Task')
    while True:
        data_received = server_socket.recvfrom(1024)
        request_number  = 1
        taskRunner(data_received, request_number)


try:
    thread_task = threading.Thread(target=task_putter())
    action_thread = threading.Thread(target=action_assigner())

    action_thread.start()
    thread_task.start()

    action_thread.join()
    thread_task.join()


except Exception as e:
    server_socket.close()

When running the code, I only get Hello Task as the result meaning that the action_thread never started. Can someone explain how to fix this?

CodePudding user response:

The problem here is that you are calling the functions that should be the "body" of each thread when creating the Threads themselves. Upon executing the line thread_task = threading.Thread(target=task_putter()) Python will resolve first the expession inside the parentheses - it calls the function task_putter, which never returns. None of the subsequent lines on your program is ever run.

What we do when creating threads, and other calls that takes callable objects as arguments, is to pass the function itself, not calling it (which will run the function and evaluate to its return value).

Just change both lines creating the threads to not put the calling parentheses on the target= argument and you will get past this point:

...

try:
    thread_task = threading.Thread(target=task_putter)

    action_thread = threading.Thread(target=action_assigner)
    ...
  • Related