python简说(二十九)线程,进程
2024-08-26 00:26:30
进程:
一些资源的集合。
一个进程里面最少有一个线程,主线程。
线程:
程序执行的最小单位。
import threading
from threading import Thread
import time
先执行主线程
def run():
time.sleep(1)
print('run...') start_time = time.time() # for i in range(5): #串行
# run() # threads = [] for i in range(20):
t1 = Thread(target=run,)
t1.start() # threads.append(t1) # for t in threads:等待所有的线程
# t.join()
# t1.join()#主线程等待子线程执行结束,只等最后一个线程 while threading.active_count()!=1: #判断子线程是否执行结束
pass end_time = time.time() print(end_time - start_time)
#多线程
for url in urls:
t = threading.Thread(target=down_load_pic,args=(url,) ) 注意参数
t.start()
def down_load_pic(url):
#下载图片的url
r = requests.get(url)
file_name = md5(r.content).hexdigest()#把文件md5之后字符串当做文件名
with open(file_name+'.jpg','wb') as fw:
fw.write(r.content)
print('%s下载完成'%file_name)
res.append(file_name)
想要返回值,只能定义一个list
电脑CPU有几个核心,就同时只能运行几个任务。 #上下文切换,cpu运行快,切换速度快 python,全局解释器锁,GIL,只能在一个cpu上运行
锁
多个线程同时去操作同一个数据的时候,可能会导致数据不正确。
要把这个数据机上锁,这样同时就只能有一个线程在操作这个数据了。
import threading count = 0 lock = threading.Lock() #申请一把锁 def run():
global count
with lock:
count+=1
# lock.acquire()#加上锁
# count+=1
# lock.release()#释放 for i in range(10):
t = threading.Thread(target=run)
t.start() while threading.active_count()!=1:
pass print(count)
守护线程:
守护主线程,主线程执行完成之后,子线程立即结束。
import threading
import time
def run():
time.sleep(5)
print('run。。。') for i in range(100):
puren = threading.Thread(target=run)
puren.setDaemon(True)#设置子线程为守护线程
puren.start() print('over')
多线程 多进程
可以利用多个cpu的。 IO密集型任务
IO消耗比较多的
多线程
input output
磁盘io
网络io CPU密集型任务
消耗CPU多的,多线程
import multiprocessing
import time
import threading
import requests
def run():
time.sleep(10)
print('run...') if __name__ == '__main__':
for i in range(10):
p = multiprocessing.Process(target=run)
p.start()
while multiprocessing.active_children(): #等待其他子进程运行结束
pass
最新文章
- 细说ASP.NET Core静态文件的缓存方式
- SQL SERVER 数据库备份的三种策略及语句
- python: extend (扩展) 与 append (追加) 的差别
- ab压力测试和CC预防
- uva1638Pole Arrangement
- Nginx缓存解决方案:SRCache
- java自动装箱的陷阱
- 关于oracle数据库(3)
- 安卓组件service
- 团队作业9——展示博客(Bata版本)
- EmguCv“线段” 结构类型学习
- Python系列之 - python运算符
- ES6知识总结
- Docker 构建镜像
- python 全栈开发,Day83(博客系统子评论,后台管理,富文本编辑器kindeditor,bs4模块)
- Linux 程序设计1:深入浅出 Linux 共享内存
- dict扩展munch,支持yaml文件
- 【RS】Stochastic PCA with ℓ2 and ℓ1 Regularization - ℓ2 和 ℓ1正则的随机 PCA
- 管道pipe与dup结合使用
- Translating Skills(1)
热门文章
- Python中self和__init__的含义与使用
- MySQL-UNIQUE
- sqli-labs(二)
- Some Useful Resources for the Future Usage
- linux文件目录管理命令
- 超简单系列:ubuntu 13.04 安装 apache2.2+mod_wsgi+Django
- uva11990 动态逆序对
- hdu 5126 cdq+Treap+BIT
- C#基础知识整理
- flask模板应用-消息闪现(flash())