Python的threading

基础用法, 通过 threading.Thread() 创建线程, 然后 start() 和 join()

import time
import threading def do_something(seconds):
print('Sleeping...')
time.sleep(seconds)
print('Done') start = time.perf_counter()
threads = [] for _ in range(10):
t = threading.Thread(target = do_something, args=[1])
t.start()
threads.append(t) for t in threads:
t.join() finish = time.perf_counter()
print('Total: {}'.format(round(finish - start, 2)))

使用线程池. 使用as_completed, 可以阻塞并按完成顺序输出结果, 而直接用executor.map()会将结果收集完成后一起返回.

import time
import threading
from concurrent import futures def do_something(seconds):
print('Sleeping...')
time.sleep(seconds)
return 'Done ' + str(seconds) start = time.perf_counter()
with futures.ThreadPoolExecutor(max_workers=3) as executor:
secs = [3, 2.5, 2, 2.2, 0.5]
results = [executor.submit(do_something, sec) for sec in secs]
for f in futures.as_completed(results):
print(f.result()) # 注意区别
with futures.ThreadPoolExecutor() as executor:
secs = [3, 2.5, 2, 2.2, 0.5]
# 下面这行实际是阻塞的
results = executor.map(do_something, secs)
for result in results:
print(result) finish = time.perf_counter()
print('Total: {}'.format(round(finish - start, 2)))

.

Python的multiprocessing

.在使用multiprocessing时, 子进程里的print()是会滞后打印的.

import time
import multiprocessing
import logging def do_something(seconds):
print('Sleeping...', seconds)
time.sleep(seconds)
return 'Done ' + str(seconds) if __name__ == '__main__':
multiprocessing.log_to_stderr()
logger = multiprocessing.get_logger()
logger.setLevel(logging.INFO)
start = time.perf_counter()
secs = [3.1, 3.5, 3.1, 3.2, 3.5, 3.3]
processes = []
for sec in secs:
p = multiprocessing.Process(target=do_something, args=(sec,))
p.start()
processes.append(p) for p in processes:
p.join() finish = time.perf_counter()
print('Total: {}'.format(round(finish - start, 2)))
print() pool = multiprocessing.Pool(processes=3)
print(pool.map(do_something, secs))
finish = time.perf_counter()
print('Total: {}'.format(round(finish - start, 2)))

.

Python的threading和multiprocessing的更多相关文章

  1. Python 线程(threading) 进程(multiprocessing)

    *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

  2. python的threading和multiprocessing模块初探

    转载于:http://blog.csdn.net/zhaozhi406/article/details/8137670

  3. python 标准库 —— 线程与同步(threading、multiprocessing)

    1. 创建线程 使用 os 下的 fork() 函数调用(仅限 Unix 系统) import os print('current process (%s) starts ...' % (os.get ...

  4. python并发编程之multiprocessing进程(二)

    python的multiprocessing模块是用来创建多进程的,下面对multiprocessing总结一下使用记录. 系列文章 python并发编程之threading线程(一) python并 ...

  5. Python 线程(threading)

    Python 的thread模块是比较底层的模块,Python的threading模块是对thread做了一些包装,可以更加方便的 被使用; 1. 使用threading 模块 # 示例一: 单线程执 ...

  6. Python之threading多线程,多进程

    1.threading模块是Python里面常用的线程模块,多线程处理任务对于提升效率非常重要,先说一下线程和进程的各种区别,如图 概括起来就是 IO密集型(不用CPU) 多线程计算密集型(用CPU) ...

  7. Python多线程 - threading

    目录 1. GIL 2. API 3. 创建子线程 4. 线程同步 4.1. 有了GIL,是否还需要同步? 4.1.1. 死锁 4.1.2. 竞争条件 4.1.3. GIL去哪儿了 4.2. Lock ...

  8. python中threading的用法

    摘自:http://blog.chinaunix.net/uid-27571599-id-3484048.html 以及:http://blog.chinaunix.net/uid-11131943- ...

  9. python中threading模块详解(一)

    python中threading模块详解(一) 来源 http://blog.chinaunix.net/uid-27571599-id-3484048.html threading提供了一个比thr ...

随机推荐

  1. Android Scroller解析

    作用 这个类封装了滚动操作,如帮我们处理手指抬起来时候的滑动操作.与ViewGroup的scrollTo(),scrollBy()的生硬式移动,Scroller提供了一个更加柔和的移动效果.Scrol ...

  2. XmlDocument.load 读文件报异常:文件正被其它线程使用,解决方法

    string filePath = Form1.getProjectFilePath(); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocu ...

  3. 为 Linux 应用程序编写 DLL

    插件和 DLL 通常是用来无须编写整个新应用程序而添加功能的极好方法. 在 Linux 中,插件和 DLL 是以动态库形式实现的. 电子商务顾问兼设计师 Allen Wilson 介绍了动态库,并且向 ...

  4. python实现广度优先搜索

    from collections import deque #解决从你的人际关系网中找到芒果销售商的问题#使用字典表示映射关系graph = {} graph["you"] = [ ...

  5. 一、MySQL基础知识

    一.背景介绍 我们每天都在访问各种网站.APP,如微信.QQ.抖音,今日头条等,这些东西上面都存在大量的信息,这些信息都需要有地方存储,存储在哪里呢?数据库. 所有我们需要开发一个网站.APP,数据库 ...

  6. 【漏洞复现】Apache Solr via Velocity template远程代码执行

    0x01 概述 Solr简介 Apache Solr 是一个开源的企业级搜索服务器.Solr 使用 Java 语言开发,主要基于 HTTP 和 Apache Lucene 实现.Apache Solr ...

  7. 详解Linux操作系统的进程

    系统 计算机运行起来以后,就是由内核和运行在内核之上的众多进程来实现的(kernel+process) 内存分为 :    线性内存: 物理内存: 计算机的所有运行都只在内存和CPU中运行! 内核空间 ...

  8. CodeForces - 1159B

    题目链接:https://vjudge.net/problem/CodeForces-1159B 题目意思:任选选两个元素,分别为a[i],a[j]. 问 都满足K*| i -  j | <= ...

  9. C程序回顾

    1.字符串操作 C中,字符串以一维数组的方式存储.字符串结束标志\0,可用scanf("%s",c);输入,以空格作为输入字符串之间的分隔符. 字符串处理函数:puts(str); ...

  10. Codeforces Round #142 (Div. 1) C. Triangles

    Codeforces Round #142 (Div. 1) C. Triangles 题目链接 今天校内选拔赛出了这个题,没做出来....自己思维能力还不够强吧.我题也给读错了.. 每次拆掉一条边, ...