python - 从线程迁移到线程

标签 python multithreading

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

相关文章:

Java 同步线程未按预期工作

python - 为什么 list.reverse 不返回列表?

用于解析程序中标识符的 Python 包(C、Scala、Lisp)?

python - 类型错误:不支持的操作数类型/: 'str' 和 'str'

multithreading - Forth 支持多线程吗?

c# - 如何查询正在运行的线程

python - Python 中的并行处理选项

python - x 和 y 必须具有相同的第一维,但具有形状 (50,) 和 (10,)

编译线程程序

java - 为什么我不应该将 PoolingHttpClientConnectionManager 与 FutureRequestExecutionService 一起使用?