[英]How to run the same function in parallel with different arguments?
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
Ie each block of aaa
and bbb
will be printed at the same time every second. 即
aaa
和bbb
每个块将每秒同时打印一次。
Actual output: only aaa is printed every second 实际输出:每秒仅打印aaa
threading.Thread(target=infiniteloop1('aaa'))
does not call infiniteloop1
on a separate thread. threading.Thread(target=infiniteloop1('aaa'))
不会在单独的线程上调用infiniteloop1
。
threading.Thread
's target
argument should be a callable. threading.Thread
的target
参数应该是可调用的。 Instead, infiniteloop1('aaa')
evaluates (=calls) infiniteloop1
even before threading.Thread
is called, and thread1.start
is never even reached. 相反,
infiniteloop1('aaa')
的计算结果(=呼叫) infiniteloop1
甚至在threading.Thread
被调用, thread1.start
从未甚至达到了。
You would have found this out on yourself if infiniteloop1
did not actually create an infinite loop. 如果
infiniteloop1
实际上没有创建无限循环,您将自己发现这一点。 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. 错误
TypeError: 'str' object is not callable
会被引发。 This is because infiniteloop1('aaa')
is evaluated to 'aaa'
which is then passed to threading.Thread
as target
. 这是因为
infiniteloop1('aaa')
被评估为'aaa'
,然后将其作为target
传递给threading.Thread
。
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). 相反,请使用
args
kwarg单独提供一个threading.Thread
及其参数(请注意,它期望可迭代,因此应将单个字符串参数作为一个元组传递)。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.