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.
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:
run_it_boy
instead of run_it_boy()
, because you don't want to call it now, but let the threading module do it.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With