"""
In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple
native threads from executing Python bytecodes at once. This lock is necessary mainly
because CPython’s memory management is not thread-safe. (However, since the GIL
exists, other features have grown to depend on the guarantees that it enforces.)
"""
"""
GIL是一个互斥锁:保证数据的安全(以牺牲效率来换取数据的安全)
阻止同一个进程内多个线程同时执行(不能并行但是能够实现并发)
并发:看起来像同时进行的
GIL全局解释器存在的原因是因为Cpython解释器的内存管理不是线程安全的
例如:
线程一正在产生一个变量还没有绑定,这时候垃圾回收线程把它回收掉了,
对线程一来说就产生了线程数据错误 垃圾回收机制
1.引用计数
2.标记清除
3.分代回收 同一个进程下的多个线程不能实现并行但是能够实现并发,多个进程下的线程能够实现并行 问题:python多线程是不是就没有用了呢?
四个任务:计算密集的任务 每个任务耗时10s
单核情况下:
多线程好一点,消耗的资源少一点
多核情况下:
开四个进程:10s多一点
开四个线程:40s多一点 四个任务:IO密集的任务 每个任务io 10s
单核情况下:
多线程好一点
多核情况下:
多线程好一点
多线程和多进程都有自己的优点,要根据项目需求合理选择 """ # 计算密集型
# from multiprocessing import Process
# from threading import Thread
# import os,time
# def work():
# res=0
# for i in range(100000000):
# res*=i
#
#
# if __name__ == '__main__':
# l=[]
# print(os.cpu_count()) # 本机为8核
# start=time.time()
# for i in range(8):
# # p=Process(target=work) #耗时9.252728939056396
# p=Thread(target=work) #耗时35.369622230529785
# l.append(p)
# p.start()
# for p in l:
# p.join()
# stop=time.time()
# print('run time is %s' %(stop-start)) # IO密集型
from multiprocessing import Process
from threading import Thread
import threading
import os,time
def work():
time.sleep(2) if __name__ == '__main__':
l=[]
print(os.cpu_count()) #本机为8核
start=time.time()
for i in range(600):
p=Process(target=work) #耗时4.699530839920044
# p=Thread(target=work) #耗时2.054128885269165
l.append(p)
p.start()
for p in l:
p.join()
stop=time.time()
print('run time is %s' %(stop-start))

最新文章

  1. 《storm实战-构建大数据实时计算读书笔记》
  2. number 数据类型的分析。
  3. python3 filter用法(举例求0~n之间的素数)
  4. Bootstrap Paginator 分页插件参数介绍及使用
  5. 查询计划Hash和查询Hash
  6. Bluetooth in Android 4.2 and 4.3(一):综述
  7. js split str.split(" "); split使用方法 在某处截字符串
  8. 转:Selenium2.0 click()不生效的解决办法
  9. Memcached的安装与使用
  10. Linux常用命令之文件处理命令
  11. 深入解读 Js 中的面向对象编程
  12. RabbitMQ 集群原理和完善
  13. vue_class 绑定_style 绑定
  14. rancher的Ingress的文件大小上传限制配置
  15. Quartz.NET 任务调度新教程
  16. 样条之贝塞尔(Bezier)
  17. 浏览器是怎样工作的:渲染引擎,HTML解析
  18. linux第四章读书笔记
  19. ABAP术语-Update Task
  20. orcale 之 SQL 数据查询

热门文章

  1. mac 使用express -e ./
  2. hdu 1133 卡特兰 高精度
  3. 下载使用IDE练习插件
  4. python 显示!到~的字符
  5. pydub音频处理库的使用
  6. UVA 10029 Edit Step Ladders ——(DAG求最长路)
  7. IDEA checkout Git 分支 弹出 Git Checkout Problem
  8. Leetcode题目102.二叉树的层次遍历(队列-中等)
  9. Nginx之 Location 的生成
  10. Flutter制作Toast会自己关闭的消息提示框