gpt4 book ai didi

python - 从线程迁移到线程

转载 作者:太空宇宙 更新时间:2023-11-03 17:35:00 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com