多线程 VS 多进程

  • 程序:一堆代码以文本形式存入一个文档
  • 进程:程序运行的一个状态
    • 包含地址空间,内存,数据栈
    • 每个进程有自己完全独立的运行环境,多进程共享数据是一个问题
  • 线程
    • 一个进程的独立运行片段,一个进程可以有多个线程
    • 轻量化的进程
    • 一个进程的多个线程间共享数据和上下文运行环境
    • 共享互斥问题
  • 全局解释器锁(GIL)
    • python代码的执行是由python虚拟机进行控制
    • 在主循环中只能有一个控制线程在执行
  • python包
    • thread:有问题,不好用,python3版本改成了_thread
    • threading:通行的包
'''
利用time函数,生成两个函数
顺序调用
计算总的运行时间'''
import timedef loop1():# ctime 得到当前时间print('Start loop 1 at :', time.ctime())# 睡眠多长时间,单位是秒time.sleep(4)print('End loop 1 at:', time.ctime())def loop2():# ctime 得到当前时间print('Start loop 2 at :', time.ctime())# 睡眠多长时间,单位是秒time.sleep(2)print('End loop 2 at:', time.ctime())def main():print("Starting at:", time.ctime())loop1()loop2()print("All done at:", time.ctime())if __name__ == '__main__':main()
Starting at: Tue Jan  1 11:08:36 2019
Start loop 1 at : Tue Jan  1 11:08:36 2019
End loop 1 at: Tue Jan  1 11:08:40 2019
Start loop 2 at : Tue Jan  1 11:08:40 2019
End loop 2 at: Tue Jan  1 11:08:42 2019
All done at: Tue Jan  1 11:08:42 2019
'''
利用time函数,生成两个函数
顺序调用
计算总的运行时间
使用多线程,缩短总时间,使用_thread'''
import time
import _thread as threaddef loop1():# ctime 得到当前时间print('Start loop 1 at :', time.ctime())# 睡眠多长时间,单位是秒time.sleep(4)print('End loop 1 at:', time.ctime())def loop2():# ctime 得到当前时间print('Start loop 2 at :', time.ctime())# 睡眠多长时间,单位是秒time.sleep(2)print('End loop 2 at:', time.ctime())def main():print("Starting at:", time.ctime())# 启动多线程的意思是用多线程去执行某个函数# 启动多线程函数为start_new_thead# 参数两个,一个是需要运行的函数名,第二是函数的参数作为元祖使用,为空则使用空元祖# 注意:如果函数只有一个参数,需要参数后有一个逗号thread.start_new_thread(loop1, ())thread.start_new_thread(loop2, ())print("All done at:", time.ctime())if __name__ == '__main__':main()while True:   #如果没有这个循环就会产生线程开始工作但是没有做完的事情发生,因为主线程在分线程结束之前就结束了time.sleep(1)
Starting at: Tue Jan  1 11:15:30 2019
All done at: Tue Jan  1 11:15:30 2019
Start loop 1 at : Tue Jan  1 11:15:30 2019
Start loop 2 at : Tue Jan  1 11:15:30 2019
End loop 2 at: Tue Jan  1 11:15:32 2019
End loop 1 at: Tue Jan  1 11:15:34 2019
#多线程,传参数
#利用time延时函数,生成两个函数
# 利用多线程调用
# 计算总运行时间
# 练习带参数的多线程启动方法
import time
# 导入多线程包并更名为thread
import _thread as threaddef loop1(in1):# ctime 得到当前时间print('Start loop 1 at :', time.ctime())# 把参数打印出来print("我是参数 ",in1)# 睡眠多长时间,单位是秒time.sleep(4)print('End loop 1 at:', time.ctime())def loop2(in1, in2):# ctime 得到当前时间print('Start loop 2 at :', time.ctime())# 把参数in 和 in2打印出来,代表使用print("我是参数 " ,in1 , "和参数  ", in2)# 睡眠多长时间,单位是秒time.sleep(2)print('End loop 2 at:', time.ctime())def main():print("Starting at:", time.ctime())# 启动多线程的意思是用多线程去执行某个函数# 启动多线程函数为start_new_thead# 参数两个,一个是需要运行的函数名,第二是函数的参数作为元祖使用,为空则使用空元祖# 注意:如果函数只有一个参数,需要参数后由一个逗号thread.start_new_thread(loop1,("王老大", ))thread.start_new_thread(loop2,("王大鹏", "王晓鹏"))print("All done at:", time.ctime())if __name__ == "__main__":main()# 一定要有while语句# 因为启动多线程后本程序就作为主线程存在# 如果主线程执行完毕,则子线程可能也需要终止while True:time.sleep(10)
  • threading的使用

    • 直接使用threading.Thread生成Thread实例

      • 1.t = threading.Thread(target = xxx, args=(xxx, )) #target是函数名,args是参数
      • 2.t.start() #气动多线程
      • 3.t.join():等待多线程执行完成
      • 守护线程,deamon
        • 如果在程序中将子线程设置成守护线程,则子线程会在主线程结束的时候自动退出
        • 一般认为,守护线程不重要或者不允许离开主线程独立运行
        • 守护线程案例能否有效果跟环境相关
      • 线程常用属性
        • threading.currentThread:返回当前线程变量
        • threading.enumerate:返回一个包含正在运行的线程的list,正在运行的线程指的是线程启动后,结束前的线程
        • threading.ativeCount:返回正在运行的线程数量,效果跟len(threading.enumerate)相同
        • thr.setName:给线程设置名字
        • thr.getName:得到线程的名字
#利用time延时函数,生成两个函数
# 利用多线程调用
# 计算总运行时间
# 练习带参数的多线程启动方法
import time
# 导入多线程处理包
import threadingdef loop1(in1):# ctime 得到当前时间print('Start loop 1 at :', time.ctime())# 把参数打印出来print("我是参数 ",in1)# 睡眠多长时间,单位是秒time.sleep(4)print('End loop 1 at:', time.ctime())def loop2(in1, in2):# ctime 得到当前时间print('Start loop 2 at :', time.ctime())# 把参数in 和 in2打印出来,代表使用print("我是参数 " ,in1 , "和参数  ", in2)# 睡眠多长时间,单位是秒time.sleep(2)print('End loop 2 at:', time.ctime())def main():print("Starting at:", time.ctime())# 生成threading.Thread实例t1 = threading.Thread(target=loop1, args=("王老大",))t1.start()t2 = threading.Thread(target=loop2, args=("王大鹏", "王小鹏"))t2.start()print("All done at:", time.ctime())if __name__ == "__main__":main()# 一定要有while语句# 因为启动多线程后本程序就作为主线程存在# 如果主线程执行完毕,则子线程可能也需要终止while True:time.sleep(10)
#加入join之后的案例
#利用time延时函数,生成两个函数
# 利用多线程调用
# 计算总运行时间
# 练习带参数的多线程启动方法
import time
# 导入多线程处理包
import threadingdef loop1(in1):# ctime 得到当前时间print('Start loop 1 at :', time.ctime())# 把参数打印出来print("我是参数 ",in1)# 睡眠多长时间,单位是秒time.sleep(4)print('End loop 1 at:', time.ctime())def loop2(in1, in2):# ctime 得到当前时间print('Start loop 2 at :', time.ctime())# 把参数in 和 in2打印出来,代表使用print("我是参数 " ,in1 , "和参数  ", in2)# 睡眠多长时间,单位是秒time.sleep(2)print('End loop 2 at:', time.ctime())def main():print("Starting at:", time.ctime())# 生成threading.Thread实例t1 = threading.Thread(target=loop1, args=("王老大",))t1.start()t2 = threading.Thread(target=loop2, args=("王大鹏", "王小鹏"))t2.start()t1.join()t2.join()print("All done at:", time.ctime())if __name__ == "__main__":main()# 一定要有while语句# 因为启动多线程后本程序就作为主线程存在# 如果主线程执行完毕,则子线程可能也需要终止while True:time.sleep(10)
#非守护线程
#主线程结束了,但是分线程依然继续执行
import time
import threadingdef fun():print("Start fun")time.sleep(2)print("end fun")print("Main thread")t1 = threading.Thread(target=fun, args=() )
t1.start()time.sleep(1)
print("Main thread end")
#守护线程案例
import time
import threadingdef fun():print("Start fun")time.sleep(2)print("end fun")print("Main thread")t1 = threading.Thread(target=fun, args=() )
# 社会守护线程的方法,必须在start之前设置,否则无效
t1.setDaemon(True)
#t1.daemon = True   #第二种设置方法
t1.start()time.sleep(1)
print("Main thread end")
import time
import threadingdef loop1():# ctime 得到当前时间print('Start loop 1 at :', time.ctime())# 睡眠多长时间,单位是秒time.sleep(6)print('End loop 1 at:', time.ctime())def loop2():# ctime 得到当前时间print('Start loop 2 at :', time.ctime())# 睡眠多长时间,单位是秒time.sleep(1)print('End loop 2 at:', time.ctime())def loop3():# ctime 得到当前时间print('Start loop 3 at :', time.ctime())# 睡眠多长时间,单位是秒time.sleep(5)print('End loop 3 at:', time.ctime())def main():print("Starting at:", time.ctime())# 生成threading.Thread实例t1 = threading.Thread(target=loop1, args=( ))# setName是给每一个子线程设置一个名字t1.setName("THR_1")t1.start()t2 = threading.Thread(target=loop2, args=( ))t2.setName("THR_2")t2.start()t3 = threading.Thread(target=loop3, args=( ))t3.setName("THR_3")t3.start()# 预期3秒后,thread2已经自动结束,time.sleep(3)# enumerate 得到正在运行子线程,即子线程1和子线程3for thr in threading.enumerate():# getName能够得到线程的名字print("正在运行的线程名字是: {0}".format(thr.getName()))print("正在运行的子线程数量为: {0}".format(threading.activeCount()))print("All done at:", time.ctime())if __name__ == "__main__":main()# 一定要有while语句# 因为启动多线程后本程序就作为主线程存在# 如果主线程执行完毕,则子线程可能也需要终止while True:time.sleep(10)
import threading
import time# 1. 类需要继承自threading.Thread
class MyThread(threading.Thread):def __init__(self, arg):super(MyThread, self).__init__()self.arg = arg# 2 必须重写run函数,run函数代表的是真正执行的功能def  run(self):time.sleep(2)print("The args for this class is {0}".format(self.arg))for i in range(5):t = MyThread(i)t.start()t.join()print("Main thread is done!!!!!!!!")
import threading
from time import sleep, ctimeloop = [4,2]class ThreadFunc:def __init__(self, name):self.name = namedef loop(self, nloop, nsec):''':param nloop: loop函数的名称:param nsec: 系统休眠时间:return:'''print('Start loop ', nloop, 'at ', ctime())sleep(nsec)print('Done loop ', nloop, ' at ', ctime())def main():print("Starting at: ", ctime())# ThreadFunc("loop").loop 跟一下两个式子相等:# t = ThreadFunc("loop")# t.loop# 以下t1 和  t2的定义方式相等t = ThreadFunc("loop")t1 = threading.Thread( target = t.loop, args=("LOOP1", 4))# 下面这种写法更西方人,工业化一点t2 = threading.Thread( target = ThreadFunc('loop').loop, args=("LOOP2", 2))# 常见错误写法#t1 = threading.Thread(target=ThreadFunc('loop').loop(100,4))#t2 = threading.Thread(target=ThreadFunc('loop').loop(100,2))t1.start()t2.start()t1.join( )t2.join()print("ALL done at: ", ctime())if __name__ == '__main__':main()112

Python系统学习第二十四课相关推荐

  1. python dataframe 新列_Python第二十四课:Pandas库(四)

    Python第二十四课:Pandas库(四)点击上方"蓝字",关注我们. 不知不觉,我们已经跨越了千难万险,从零开始,一步步揭开了Python神秘的面纱.学到至今,回过头,才晓得自 ...

  2. NeHe OpenGL第二十四课:扩展

    NeHe OpenGL第二十四课:扩展 扩展,剪裁和TGA图像文件的加载: 在这一课里,你将学会如何读取你显卡支持的OpenGL的扩展,并在你指定的剪裁区域把它显示出来.   这个教程有一些难度,但它 ...

  3. Python-opencv学习第二十九课:高斯双边模糊

    Python-opencv学习第二十九课:高斯双边模糊 文章目录 Python-opencv学习第二十九课:高斯双边模糊 一.学习部分 二.代码部分 1.引入库 2.读入数据 3.完整代码 三.运行结 ...

  4. 游戏策划学习第二十四天

    游戏策划学习第二十四天 5/23 5.社交:社交影响与关联性 6.稀缺:稀缺性与渴望 7.未知:未知性与好奇心 8.亏损:亏损与逃避心 最近在玩百闻牌,那就用百闻牌来思考这四项内容. 5.社交并不只是 ...

  5. 实践数据湖iceberg 第二十四课 iceberg元数据详细解析

    系列文章目录 实践数据湖iceberg 第一课 入门 实践数据湖iceberg 第二课 iceberg基于hadoop的底层数据格式 实践数据湖iceberg 第三课 在sqlclient中,以sql ...

  6. JavaScript高级程序设计第四版学习--第二十四章

    title: JavaScript高级程序设计第四版学习–第二十四章 date: 2021-5-31 10:46:01 author: Xilong88 tags: JavaScript 本章内容: ...

  7. 风炫安全web安全学习第二十八节课 CSRF攻击原理

    风炫安全web安全学习第二十八节课 CSRF攻击原理 CSRF 简介 跨站请求伪造 (Cross-Site Request Forgery, CSRF),也被称为 One Click Attack 或 ...

  8. Python界面编程第十四课:Pyside2 (Qt For Python)使用Calendar创建日历

    QCalendar 是什么? QCalendar对象使用特定系统规则将年.月和日映射到特定的日期(最终由它的Julian天数标识). 默认的QCalendar() 是一个扩展的Gregorian日历, ...

  9. 全民一起玩Python提高篇第十四课:函数式编程初步(上)

    函数与数字.字符串.列表等一样,本质上都是某种存放在内存中的数据类型,都可以用一个名字(变量名.函数名 -- )指向它 一个函数与一个数字.字符串等一样,都可以赋值给一个变量.比如,如果 f 是一个函 ...

  10. 学习淘淘商城第二十四课(前台系统工程搭建)

    上节课我们一起学习了添加商品的实现,这节课我们学习搭建前台系统工程. 我们先来看一下淘淘商城的首页,如下图所示. 我们再来看看淘淘商城的系统架构图,我们目前只是完成了后台管理系统和商品服务,还有很多没 ...

最新文章

  1. lnmp集成开发环境安装pdo_dblib扩展
  2. Intuit的Alex Balazs访谈
  3. Matlab 非线性规划问题模型代码
  4. 一条sql语句,要修改一个字段的俩个值,比如把字段sex中的男改为女,女改为男...
  5. Hibernate三大组成部分
  6. python安装scipy出现红字_windows下安装numpy,scipy遇到的问题总结
  7. Java的数据类型及其封装器类
  8. c语言高斯白序列x,C语言程序设计程设计指导书(晓庄).doc
  9. Pytorch可视化工具 —— TensorBoard
  10. AjaxControlToolKit之AutoCompleteExtender用法
  11. mt4双线macd_指标小课堂|学院首创!独家手机MT4双线MACD指标设置教程
  12. 如何使用计算机文件共享,两台电脑如何共享文件?【步骤图解】
  13. 什么软件能测试显卡功耗,测试方案及测试平台
  14. LeetCode1156. 单字符重复子串的最大长度
  15. 知识点 - 快速沃尔什变换
  16. spring框架使用JavaMailSenderImpl发送邮件
  17. python画花的代码怎么打不开_怎么用python画玫瑰花,求大神贴代码,感激不尽
  18. Java学习之路-----Java基础简介,基础语法,Java标识符,修饰符,关键字与注释
  19. 美摄SDK Alpha产品说明书
  20. 三极管应用电路---低通滤波电路

热门文章

  1. php织梦cms 安装教程,Linux服务器上安装织梦CMS,linux服务器织梦cms_PHP教程
  2. DataX工具的基本使用
  3. CSS运用中所体会到的方法
  4. 解决——》feign文件下载时报错feign.codec.EncodeException: not in non blocking mode
  5. 关于ireport中文不显示问题
  6. 自动驾驶两大路线对决,渐进式玩家为何更容易得人心?
  7. 可解释机器学习- LIME模型讲解|interpretable machine learning-LIME
  8. 如何在React.js文件中设置标签的背景图片
  9. Docker关闭容器命令(docker stop)
  10. win2003服务器360修复漏洞打不开网页,360浏览器打不开网页,教您怎样解决360浏览器打不开网页...