线程与threading模块
线程
进程内一个相对独立的、可调度的执行单元,是系统独立调度和分派CPU的基本单位。在单个进程中同时运行多个线程完成不同的工作,称为多线程。
同一进程内的多个线程是共享该进程的资源。
创建新的线程开销要远远小于开启新的进程。
threading模块
线程的threading模块与进程的multiprocessing模块很类似。
模块下的类:
Thread
active_count
enumerate
current_thread
方法:
start()
join()
daemon() 守护线程和守护进程有点不一样。主线程在执行完所有非守护线程后,主线程结束,守护线程随之结束。
示例:
rom threading import Thread,current_thread,active_count,enumerate
import time
def bar():
print('%s is running'%current_thread().getName() )
time.sleep(2)
print('%s is over'%current_thread().getName() )
def foo():
print('%s is running' % current_thread().getName())
time.sleep(5)
print('%s is over' % current_thread().getName())
if __name__ == '__main__':
t1=Thread(target=bar)
t2=Thread(target=foo)
t1.start()
t2.daemon=True
t2.start()
print(enumerate())
print(active_count())
print('%s is 主线程' %current_thread().getName())
输出:
Thread-1 is running
Thread-2 is running
[<_MainThread(MainThread, started 816)>, <Thread(Thread-1, started 7528)>, <Thread(Thread-2, started daemon 13788)>]
3
MainThread is 主线程
Thread-1 is over
PS:
多线程用于IO密集型,如socket,爬虫,web
多进程用于计算密集型,如金融分析
from multiprocessing import Process
from threading import Thread
import time
def foo():
sum=0
for i in range(100000000):
sum+=i if __name__ == '__main__':
start_time=time.time()
n=os.cpu_count()
l=[]
for i in range(n):
t=Thread(target=foo,) #41s
# p=Process(target=foo,) #9.89s
# l.append(p)
l.append(t)
# p.start()
t.start()
for p in l:
# p.join()
p.join()
print('time:',time.time()-start_time)
作业:
三个任务,一个接收用户输入,一个将用户输入的内容格式化成大写,一个将格式化后的结果存入文件。
from threading import Thread
msg_l=[] #
format_l=[] #这两个是关键呀,相当于进程中的全局变量,进程中的数据(全局变量)是共享的,任何一个线程都可以访问的到。
def talk(): #三个函数,开启三个线程,做到各司其职,互不干涉,存取数据到进程中的全局变量取就可以了。
while True:
msg=input('>>: ').strip()
if not msg:continue
msg_l.append(msg) def format_msg():
while True:
if msg_l:
res=msg_l.pop()
format_l.append(res.upper()) def save():
while True:
if format_l:
with open('db.txt','a',encoding='utf-8') as f:
res=format_l.pop()
f.write('%s\n' %res) if __name__ == '__main__':
t1=Thread(target=talk)
t2=Thread(target=format_msg)
t3=Thread(target=save)
t1.start()
t2.start()
t3.start()
思路还是很6的。
线程与threading模块的更多相关文章
- <python的线程与threading模块>
<python的线程与threading模块> 一 线程的两种调用方式 threading 模块建立在thread 模块之上.thread模块以低级.原始的方式来处理和控制线程,而thre ...
- python全栈开发 * 进程池,线程理论 ,threading模块 * 180727
一.进程池 (同步 异步 返回值) 缺点: 开启进程慢 几个CPU就能同时运行几个程序 进程的个数不是无线开启的 应用: 100个任务 进程池 如果必须用多个进程 且是高计算型 没有IO型的程序 希望 ...
- {Python之线程} 一 背景知识 二 线程与进程的关系 三 线程的特点 四 线程的实际应用场景 五 内存中的线程 六 用户级线程和内核级线程(了解) 七 python与线程 八 Threading模块 九 锁 十 信号量 十一 事件Event 十二 条件Condition(了解) 十三 定时器
Python之线程 线程 本节目录 一 背景知识 二 线程与进程的关系 三 线程的特点 四 线程的实际应用场景 五 内存中的线程 六 用户级线程和内核级线程(了解) 七 python与线程 八 Thr ...
- Python 浅析线程(threading模块)和进程(process)
线程是操作系统能够进行运算调度的最小单位.它被包含在进程之中,是进程中的实际运作单位.一条线程指的是进程中一个单一顺序的控制流,一个进程中可以并发多个线程,每条线程并行执行不同的任务 进程与线程 什么 ...
- Python的进程、线程和threading模块
(注:本文部分内容摘自互联网,由于作者水平有限,不足之处,还望留言指正.) 怀念在学校念书的时候,我不小心触碰到了错误,老师会说:你错了:而我却总是倔强得以为自己没错.我的内心是不屑的,直到在真理面前 ...
- Python的并发并行[1] -> 线程[0] -> threading 模块
threading模块 / threading Module 1 常量 / Constants Pass 2 函数 / Function 2.1 setprofile()函数 函数调用: thread ...
- python全栈开发 * 线程锁 Thread 模块 其他 * 180730
一,线程Thread模块1.效率更高(相对于进程) import time from multiprocessing import Process from threading import Thre ...
- python成长之路【第十一篇】:网络编程之线程threading模块
一.threading模块介绍 threading 模块建立在 _thread 模块之上.thread 模块以低级.原始的方式来处理和控制线程,而 threading 模块通过对 thread 进行二 ...
- Python——threading模块(线程)
一.threading模块的对象 Thread:表示一个执行线程的对象 Lock:锁 Rlock:可重入锁对象 Condition:条件变量对象,使得一个线程等待另一个线程满足特定的“条件” Even ...
随机推荐
- sql快速删除所用表,视图,存储过程
[http://www.th7.cn/db/mssql/2011-07-07/10127.shtml#userconsent#] 删除用户表 .select 'DROP TABLE '+name fr ...
- java第八次作业:课堂上发布的前5张图片(包括匿名对象、单例模式恶汉式、自动生成对象、args[]数组使用、静态关键字)
- Android读书笔记一
通过本章的学习真实体会到“移植”的概念:为特定设备定制Android的过程,但是移植的过程中开发最多的就是支持各种硬件设备的Linux驱动程序,本章对Android和Linux做了总体介绍.接着介绍了 ...
- 教程笔记《JavaScript深入浅出》
一.数据类型 javascript是弱数据类型语言,不需要显式的定义类型,一共有如下六种数据类型 五种基本类型:number,string,boolean,null,undefined 一种复合类型: ...
- Applied Nonparametric Statistics-lec1
参考网址: https://onlinecourses.science.psu.edu/stat464/node/2 Binomial Distribution Normal Distribution ...
- JAVA基础篇—异常
五种常见异常 1.NullPointerException 空指针 2.ClassNotFoundException 指定类不存在 3.ArithmeticException运算异常 4.ArrayI ...
- ACM-ICPC 2018 徐州赛区网络预赛 B. BE, GE or NE
In a world where ordinary people cannot reach, a boy named "Koutarou" and a girl named &qu ...
- selenium2 TestNG参数化
想要参数化,首先要加入@Parameters({"参数1","参数2"}) package com.demo.test; import java.util.co ...
- BZOJ 2217: [Poi2011]Lollipop
若sum可行 sum-2一定可行 序列和为ans 找出和ans奇偶性不同的最大的ans,即最靠左或最靠右的1的位置 更新答案 有spj #include<cstdio> using nam ...
- loj2013 「SCOI2016」幸运数字
点分治+线性基 (为了这六个字窝调了一下午一晚上QAQ #include <iostream> #include <cstring> #include <cstdio&g ...