进程:
一些资源的集合。
一个进程里面最少有一个线程,主线程。
线程:
程序执行的最小单位。
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

最新文章

  1. 细说ASP.NET Core静态文件的缓存方式
  2. SQL SERVER 数据库备份的三种策略及语句
  3. python: extend (扩展) 与 append (追加) 的差别
  4. ab压力测试和CC预防
  5. uva1638Pole Arrangement
  6. Nginx缓存解决方案:SRCache
  7. java自动装箱的陷阱
  8. 关于oracle数据库(3)
  9. 安卓组件service
  10. 团队作业9——展示博客(Bata版本)
  11. EmguCv“线段” 结构类型学习
  12. Python系列之 - python运算符
  13. ES6知识总结
  14. Docker 构建镜像
  15. python 全栈开发,Day83(博客系统子评论,后台管理,富文本编辑器kindeditor,bs4模块)
  16. Linux 程序设计1:深入浅出 Linux 共享内存
  17. dict扩展munch,支持yaml文件
  18. 【RS】Stochastic PCA with ℓ2 and ℓ1 Regularization - ℓ2 和 ℓ1正则的随机 PCA
  19. 管道pipe与dup结合使用
  20. Translating Skills(1)

热门文章

  1. Python中self和__init__的含义与使用
  2. MySQL-UNIQUE
  3. sqli-labs(二)
  4. Some Useful Resources for the Future Usage
  5. linux文件目录管理命令
  6. 超简单系列:ubuntu 13.04 安装 apache2.2+mod_wsgi+Django
  7. uva11990 动态逆序对
  8. hdu 5126 cdq+Treap+BIT
  9. C#基础知识整理
  10. flask模板应用-消息闪现(flash())