首页 / PYTHON / 如何在Python中使用线程?
如何在Python中使用线程?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了如何在Python中使用线程?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2415字,纯文字阅读大概需要4分钟。
内容图文
![如何在Python中使用线程?](/upload/InfoBanner/zyjiaocheng/717/26526d9d2a9f4fd1a84f607a11d7f453.jpg)
我试图理解Python中的线程.我看过文档和示例,但坦率地说,很多例子都过于复杂,我很难理解它们.
你如何清楚地展示为多线程划分的任务?
解决方法:
自从2010年提出这个问题以来,如何使用map和pool的python进行简单的多线程处理已经有了真正的简化.
下面的代码来自一篇文章/博客文章,你绝对应该检查(没有隶属关系) – Parallelism in one line: A Better Model for Day to Day Threading Tasks.我将在下面总结 – 它最终只是几行代码:
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
results = pool.map(my_function, my_array)
哪个是多线程版本:
results = []
for item in my_array:
results.append(my_function(item))
描述
Map is a cool little function, and the key to easily injecting parallelism into your Python code. For those unfamiliar, map is something lifted from functional languages like Lisp. It is a function which maps another function over a sequence.
Map handles the iteration over the sequence for us, applies the function, and stores all of the results in a handy list at the end.
履行
Parallel versions of the map function are provided by two libraries:multiprocessing, and also its little known, but equally fantastic step child:multiprocessing.dummy.
multiprocessing.dummy与多处理模块but uses threads instead完全相同(an important distinction – 对CPU密集型任务使用多个进程; IO(和期间)IO的线程):
multiprocessing.dummy replicates the API of multiprocessing but is no more than a wrapper around the threading module.
import urllib2
from multiprocessing.dummy import Pool as ThreadPool
urls = [
'http://www.python.org',
'http://www.python.org/about/',
'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
'http://www.python.org/doc/',
'http://www.python.org/download/',
'http://www.python.org/getit/',
'http://www.python.org/community/',
'https://wiki.python.org/moin/',
]
# make the Pool of workers
pool = ThreadPool(4)
# open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
# close the pool and wait for the work to finish
pool.close()
pool.join()
时间结果如下:
Single thread: 14.4 seconds
4 Pool: 3.1 seconds
8 Pool: 1.4 seconds
13 Pool: 1.3 seconds
传递多个参数(如only in Python 3.3 and later所示):
要传递多个数组:
results = pool.starmap(function, zip(list_a, list_b))
或传递常量和数组:
results = pool.starmap(function, zip(itertools.repeat(constant), list_a))
如果您使用的是早期版本的Python,则可以通过this workaround传递多个参数.
(感谢user136036的有用评论)
内容总结
以上是互联网集市为您收集整理的如何在Python中使用线程?全部内容,希望文章能够帮你解决如何在Python中使用线程?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。