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. VS code key shortcuts for windows

    mac上的快捷键,尽量是选择像我用vs studio上靠近. ctrl+K+S: 显示快捷键列 ctrl+shift+p: 系统配置命令行 ctrl+p:项目中文件列表,选择文件 Alt+M:当前文件 ...

  2. mac php Swoole入门

    一. swoole 扩展安装 安装前必须保证系统已经安装了下列软件 php-7.0 或更高版本 gcc-4.8 或更高版本 make autoconf pcre (CentOS系统可以执行命令:yum ...

  3. prometheus学习系列一: Prometheus简介

    Prometheus简介 prometheus受启发于Google的Brogmon监控系统(相似kubernetes是从Brog系统演变而来), 从2012年开始由google工程师Soundclou ...

  4. 《linux就该这么学》课堂笔记06 编写shell脚本、if、for

    1.1.脚本的两种方式 交互式(Interactive):用户每输入一条命令就立即执行. 批处理(Batch):由用户事先编写好一个完整的Shell脚本,Shell会一次性执行脚本中诸多的命令. 1. ...

  5. Tessy — 嵌入式软件单元测试/ 集成测试工具

    Tessy 源自戴姆勒- 奔驰公司的软件技术实验室,由德国Hitex 公司负责全球销售及技术支持服务,是一款专门针对嵌入式软件进行单元/ 集成测试的工具.它可以对C/C++ 代码进行单元.集成测试,可 ...

  6. PAT 乙级 1013.数素数 C++/Java

    题目来源 令 P​i​​ 表示第 i 个素数.现任给两个正整数 M≤N≤10​4​​,请输出 P​M​​ 到 P​N​​ 的所有素数. 输入格式: 输入在一行中给出 M 和 N,其间以空格分隔. 输出 ...

  7. matplotlib---插值画二维、三维图

    一.画二维图 1.原始数据(x,y) import matplotlib.pyplot as plt import numpy as np #数据 X = np.array(list(i for i ...

  8. Educational Codeforces Round 65 (Rated for Div. 2)题解

    Educational Codeforces Round 65 (Rated for Div. 2)题解 题目链接 A. Telephone Number 水题,代码如下: Code #include ...

  9. git分布式版本控制系统的概述和安装

    Git历史 同生活中的许多伟大赛事一样,Git诞生于一个极富纷争大举创新的年代.Linux内核开源项目有着为数众广的参与者.绝大多数的Linux内核维护工作都花在了提交补丁和保存归档的繁琐事务上(19 ...

  10. jmeter APP接口压力测试

    第一步:获取开发文档,了解接口地址和参数名 第二步:jmeter中添加需要测试的接口 a.设计APP的接口框架: b.http请求默认值设置如下: c.接口中应需要用到sign字段,加密字符串与时间戳 ...