-1

I want to run the same function multiple times, each time with different arguments whilst using multithreading or multiprocessing. This is my code so far:

import threading
import time

def infiniteloop1(a):
    while True:
        print(a)
        time.sleep(1)


thread1 = threading.Thread(target=infiniteloop1('aaa'))
thread1.start()

thread2 = threading.Thread(target=infiniteloop1('bbb'))
thread2.start()

Expected output:

aaa
bbb
aaa
bbb

I.e. each block of aaa and bbb will be printed at the same time every second.

Actual output: only aaa is printed every second

Or Katz
  • 19
  • 1
  • 3

1 Answers1

5

threading.Thread(target=infiniteloop1('aaa')) does not call infiniteloop1 on a separate thread.

threading.Thread's target argument should be a callable. Instead, infiniteloop1('aaa') evaluates (=calls) infiniteloop1 even before threading.Thread is called, and thread1.start is never even reached.

You would have found this out on yourself if infiniteloop1 did not actually create an infinite loop. For example, if it was to simply return the argument it got:

def infiniteloop1(a):
    return a

thread1 = threading.Thread(target=infiniteloop1('aaa'))

the error TypeError: 'str' object is not callable would have been raised. This is because infiniteloop1('aaa') is evaluated to 'aaa' which is then passed to threading.Thread as target.


Instead, provide a callable to threading.Thread and the arguments for it separately with the args kwarg (and keep in mind that it expects an iterable, so a single string argument should be passed as a one-tuple).

thread1 = threading.Thread(target=infiniteloop1, args=('aaa',))
thread1.start()

thread2 = threading.Thread(target=infiniteloop1, args=('bbb',))
thread2.start()

output:

aaa
bbb
bbbaaa  
aaa
bbb
aaa
bbb
aaa
bbb
aaabbb

aaabbb

bbb
aaa
aaabbb
DeepSpace
  • 78,697
  • 11
  • 109
  • 154