'Python Threading Not Working as it supposed

So i have a function and i want to run this function several times with different args it should be like this right

def a(arg):
  print(arg)
a(arg1)
a(arg2)
a(arg3)
a(arg4)

but with threading we can just do this

def a(arg):
  print(arg)
args = ["arg1","arg2","arg3","arg4"]
for arg in args:
t = threading.Thread(target=a, args = (arg, ))
t.start()

in my original code there are 50 other args and when i start my code it just starts 20 of them and after a while it just decreases to 3 or 1 or 2 it doesn't matter it just decreases and never goes back to normal why would it be like this



Solution 1:[1]

You have some identation problems (and forgot to change the target) in your code, but this example works fine for me

import threading

def a(arg):
  print(arg)

args = []
for i in range(50):
  args.append("arg" + str(i))

for arg in args:
  t = threading.Thread(target=a, args=(arg, ))
  t.start()

This prints out

arg0
arg1
arg2
...
arg49

Solution 2:[2]

I really highly recommend using a threadpool for this sort of stuff.

from multiprocessing.pool import ThreadPool


with ThreadPool() as pool:
    pool.map(a, args)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fooiey
Solution 2 Frank Yellin