Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically creating functions and threads in Python

I have an array filled with commands and I want to execute all of the commands at the same time.

So far I have:

import threading

...

def MyThread0():
    exec commandArray[0]

def MyThread1():
    exec commandArray[1]

t1 = threading.Thread(target=MyThread0(), args=[]).start()
t2 = threading.Thread(target=MyThread1(), args=[]).start()

While this may still be acceptable if there are only two threads (it seems to work, at least), it certainly is not if the length of the commandArray is unknown at runtime. How do I do this efficiently for x number of threads?

PS: It is entirely possible that all of this is junk as I'm new to multithreading. Constructive criticism is highly appreciated.

like image 924
vpriesner Avatar asked Feb 07 '23 19:02

vpriesner


1 Answers

If I understand your problem correctly, it should be like this:

    import threading

    ...
    command_array = ...
    number_of_commands = len(command_array)
    ...

    def run_the_command(index):
        exec command_array[index]

    threads = []
    for i in range(number_of_commands):    
        t = threading.Thread(target=run_the_command, args=(i,))
        t.start()
        threads.append(t)

Note that:

  1. Pass run_it_boy instead of run_it_boy(), because you don't want to call it now, but let the threading module do it.
  2. It is encouraged to use snake_case for function/method name and variable name, CamelCase is for class name.

Alternative

In my opinion it is better to use something called thread pool.

like image 108
fikr4n Avatar answered Feb 09 '23 11:02

fikr4n