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. 打造属于你的提供者(Provider = Strategy + Factory Method) 设计模式 - Provider Pattern(提供者模式)

    打造属于你的提供者(Provider = Strategy + Factory Method)   1.1.1 摘要 在日常系统设计中,我们也许听说过提供者模式,甚至几乎每天都在使用它,在.NET F ...

  2. PHP的SPL标准库

    1,简介 SPL,全称 Standard PHP Library 中文是 标准PHP类库.是php内置的一些拓展类和拓展接口,其内容包含数据结构.迭代器.接口.异常.SPL函数,文件处理等内容.SPL ...

  3. 性能测试基础---测试流程,LR安装

    ·性能测试流程详解: 一般来说,性能测试通常可以分为以下过程: ·前期分析.测试计划.测试方案.测试环境的搭建.测试数据的准备.测试脚本的开发.测试场景的设计.测试场景的实现和执行.资源的监控.分析结 ...

  4. 拖拽插件SortableJS

    在项目中,经常会遇到一些涉及到拖拽的需求,github上面有一个开源的SortableJS的插件,支持Vue,React,Angular等多种框架,实现效果很好,基本可以满足大部分的需求,下面就第一次 ...

  5. STL str replace

    #include <iostream> #include <string> using namespace std; void main() { string s=" ...

  6. 实时查看mysql当前连接数

    如何实时查看mysql当前连接数? 1.查看当前所有连接的详细资料:./mysqladmin -uadmin -p -h10.140.1.1 processlist 2.只查看当前连接数(Thread ...

  7. 让iOS 开发更便捷-JSONConverter

    JSONConverter是MAC上iOS开发的辅助小工具,可以快速的把json数据转换生成对应的模型类属性,目前支持Objective-C.Swift以及目前流行的第三方库: SwiftyJSON. ...

  8. UI系统的作用

    1.向用户展示信息: 2.将用于与系统的交互解释为指令.

  9. docker 服务无法启动

    重装以后仍然不行,dockerd可以运行,但是systemctl start docker.service不行,后来在编辑一个文件时,提示没有空间可以保存,结果一查,发现服务器空间基本占满了, 通过 ...

  10. Redis笔记搬迁

      Redis原理 从不同的角度来详细介绍redis 存储方式 数据结构 Redis的过期策略 数据淘汰策略 高可用 主从复制 分布式缓存 哨兵 缓存异常 缓存穿透 缓存雪崩 缓存与数据库数据一致性 ...