在 Python 2 中,我使用模块 thread
轻松创建新线程,执行以下操作:
thread.start_new_thread(function_name, (arguments_tuple,))
我知道我可以在 Python 3 中运行相同的代码,只是我必须用 import _thread
替换 import thread
语句。但正如 Python 文档中所解释的:
This module provides low-level primitives for working with multiple threads (also called light-weight processes or tasks) — multiple threads of control sharing their global data space. For synchronization, simple locks (also called mutexes or binary semaphores) are provided. The threading module provides an easier to use and higher-level threading API built on top of this module.
如何将该代码段迁移到新的模块语法?
最佳答案
新模块旨在面向 OOP,因此使用线程
的示例如下:
import time
from threading import Thread
def sleeper(i):
print "thread %d sleeps for 5 seconds" % i
time.sleep(5)
print "thread %d woke up" % i
for i in range(10):
t = Thread(target=sleeper, args=(i,))
t.start()
将 import thread
更改为 from threading import Thread
,并将 start_new_thread(func, (args,)
更改为 Thread(target= func, args=(args,).start()
就可以了。
关于python - 从线程迁移到线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31320779/