问题描述
所以我的目标是让do_something()
函数启动其自己的线程,以便do_something()
可以并行运行,而不必等待上一个函数完成.问题在于,它似乎不是多线程的(意味着一个线程在另一个线程开始之前就完成了).
So my goal is to have the do_something()
function kickoff its own thread so that do_something()
can run in parallel instead of having to wait for the previous one to finish. The problem is that it seems like it is not multithreading (meaning one thread finishes before the other one starts).
for i in range(len(array_of_letters)):
if i == "a":
t = threading.Thread(target=do_something())
print "new thread started : %s"%(str(threading.current_thread().ident))
t.start()
我在do_something()
函数中也有一个current_thread().ident
,但是似乎启动的线程的标识与从其运行python脚本的主线程相同.我认为我的方法是不正确的.
I also have a current_thread().ident
inside of the do_something()
function but it seems like the identity of the thread that is started is the same as the main thread that the python script is running from. I think my approach is incorrect.
推荐答案
这是常见错误,容易出错.
This is a common and easy to fall for mistake.
target=do_something()
只是在主线程中一次执行您的函数,然后将None
(我想是您函数的返回值)作为target
函数传递给线程,这不会触发任何可见的错误;但是什么也没做.
target=do_something()
just executes your function at once in the main thread and passes None
(the returning value of your function I suppose) as target
function to the thread, which does not trigger any visible error; but does nothing either.
您必须传递实际函数而不是结果:
you have to pass the actual function not the result:
t = threading.Thread(target=do_something)
会更好
这篇关于同时运行多个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!