多线程和多进程是什么自行google补脑

  对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂。所以,这里力图用简单的例子,让你对多线程有个初步的认识。

单线程

  在好些年前的MS-DOS时代,操作系统处理问题都是单任务的,我想做听音乐和看电影两件事儿,那么一定要先排一下顺序。

(好吧!我们不纠结在DOS时代是否有听音乐和看影的应用。^_^)

  1. from time import ctime,sleep
  2.  
  3. def music():
  4. for i in range(2):
  5. print "I was listening to music. %s" %ctime()
  6. sleep(1)
  7.  
  8. def move():
  9. for i in range(2):
  10. print "I was at the movies! %s" %ctime()
  11. sleep(5)
  12.  
  13. if __name__ == '__main__':
  14. music()
  15. move()
  16. print "all over %s" %ctime()

  我们先听了一首音乐,通过for循环来控制音乐的播放了两次,每首音乐播放需要1秒钟,sleep()来控制音乐播放的时长。接着我们又看了一场电影,

每一场电影需要5秒钟,因为太好看了,所以我也通过for循环看两遍。在整个休闲娱乐活动结束后,我通过

  1. print "all over %s" %ctime()

看了一下当前时间,差不多该睡觉了。

运行结果:

  1. >>=========================== RESTART ================================
  2. >>>
  3. I was listening to music. Thu Apr 17 10:47:08 2014
  4. I was listening to music. Thu Apr 17 10:47:09 2014
  5. I was at the movies! Thu Apr 17 10:47:10 2014
  6. I was at the movies! Thu Apr 17 10:47:15 2014
  7. all over Thu Apr 17 10:47:20 2014

  

  其实,music()和move()更应该被看作是音乐和视频播放器,至于要播放什么歌曲和视频应该由我们使用时决定。所以,我们对上面代码做了改造:

  1. #coding=utf-8
  2. import threading
  3. from time import ctime,sleep
  4.  
  5. def music(func):
  6. for i in range(2):
  7. print "I was listening to %s. %s" %(func,ctime())
  8. sleep(1)
  9.  
  10. def move(func):
  11. for i in range(2):
  12. print "I was at the %s! %s" %(func,ctime())
  13. sleep(5)
  14.  
  15. if __name__ == '__main__':
  16. music(u'爱情买卖')
  17. move(u'阿凡达')
  18.  
  19. print "all over %s" %ctime()

  对music()和move()进行了传参处理。体验中国经典歌曲和欧美大片文化。

运行结果:

  1. >>> ======================== RESTART ================================
  2. >>>
  3. I was listening to 爱情买卖. Thu Apr 17 11:48:59 2014
  4. I was listening to 爱情买卖. Thu Apr 17 11:49:00 2014
  5. I was at the 阿凡达! Thu Apr 17 11:49:01 2014
  6. I was at the 阿凡达! Thu Apr 17 11:49:06 2014
  7. all over Thu Apr 17 11:49:11 2014

多线程

  科技在发展,时代在进步,我们的CPU也越来越快,CPU抱怨,P大点事儿占了我一定的时间,其实我同时干多个活都没问题的;于是,操作系统就进入了多任务时代。我们听着音乐吃着火锅的不在是梦想。

  python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补,为了不浪费你和时间,所以我们直接学习threading 就可以了。

继续对上面的例子进行改造,引入threadring来同时播放音乐和视频:

  1. #coding=utf-8
  2. import threading
  3. from time import ctime,sleep
  4.  
  5. def music(func):
  6. for i in range(2):
  7. print "I was listening to %s. %s" %(func,ctime())
  8. sleep(1)
  9.  
  10. def move(func):
  11. for i in range(2):
  12. print "I was at the %s! %s" %(func,ctime())
  13. sleep(5)
  14.  
  15. threads = []
  16. t1 = threading.Thread(target=music,args=(u'爱情买卖',))
  17. threads.append(t1)
  18. t2 = threading.Thread(target=move,args=(u'阿凡达',))
  19. threads.append(t2)
  20.  
  21. if __name__ == '__main__':
  22. for t in threads:
  23. t.setDaemon(True)
  24. t.start()
  25.  
  26. print "all over %s" %ctime()

import threading

首先导入threading 模块,这是使用多线程的前提。

threads = []

t1 = threading.Thread(target=music,args=(u'爱情买卖',))

threads.append(t1)

  创建了threads数组,创建线程t1,使用threading.Thread()方法,在这个方法中调用music方法target=music,args方法对music进行传参。 把创建好的线程t1装到threads数组中。

  接着以同样的方式创建线程t2,并把t2也装到threads数组。

for t in threads:

  t.setDaemon(True)

  t.start()

最后通过for循环遍历数组。(数组被装载了t1和t2两个线程)

setDaemon()

  setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。

start()

开始线程活动。

运行结果:

  1. >>> ========================= RESTART ================================
  2. >>>
  3. I was listening to 爱情买卖. Thu Apr 17 12:51:45 2014 I was at the 阿凡达! Thu Apr 17 12:51:45 2014 all over Thu Apr 17 12:51:45 2014

  从执行结果来看,子线程(muisc 、move )和主线程(print "all over %s" %ctime())都是同一时间启动,但由于主线程执行完结束,所以导致子线程也终止。

继续调整程序:

  1. ...
  2. if __name__ == '__main__':
  3. for t in threads:
  4. t.setDaemon(True)
  5. t.start()
  6.  
  7. t.join()
  8.  
  9. print "all over %s" %ctime()

  我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。

  注意:  join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。

运行结果:

  1. >>> ========================= RESTART ================================
  2. >>>
  3. I was listening to 爱情买卖. Thu Apr 17 13:04:11 2014 I was at the 阿凡达! Thu Apr 17 13:04:11 2014
  4.  
  5. I was listening to 爱情买卖. Thu Apr 17 13:04:12 2014
  6. I was at the 阿凡达! Thu Apr 17 13:04:16 2014
  7. all over Thu Apr 17 13:04:21 2014

  从执行结果可看到,music 和move 是同时启动的。

  开始时间4分11秒,直到调用主进程为4分22秒,总耗时为10秒。从单线程时减少了2秒,我们可以把music的sleep()的时间调整为4秒。

  1. ...
  2. def music(func):
  3. for i in range(2):
  4. print "I was listening to %s. %s" %(func,ctime())
  5. sleep(4)
  6. ...

执行结果:

  1. >>> ====================== RESTART ================================
  2. >>>
  3. I was listening to 爱情买卖. Thu Apr 17 13:11:27 2014I was at the 阿凡达! Thu Apr 17 13:11:27 2014
  4.  
  5. I was listening to 爱情买卖. Thu Apr 17 13:11:31 2014
  6. I was at the 阿凡达! Thu Apr 17 13:11:32 2014
  7. all over Thu Apr 17 13:11:37 2014

  子线程启动11分27秒,主线程运行11分37秒。

  虽然music每首歌曲从1秒延长到了4 ,但通多程线的方式运行脚本,总的时间没变化。

本文从感性上让你快速理解python多线程的使用,更详细的使用请参考其它文档或资料。

==========================================================

class threading.Thread()说明:

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

This constructor should always be called with keyword arguments. Arguments are:

  group should be None; reserved for future extension when a ThreadGroup class is implemented.

  target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

  name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

  args is the argument tuple for the target invocation. Defaults to ().

  kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing

anything else to the thread.

Python的多线程理解,转自虫师https://www.cnblogs.com/fnng/p/3670789.html的更多相关文章

  1. 【Python】分析自己的博客 https://www.cnblogs.com/xiandedanteng/p/?page=XX,看每个月发帖量是多少

    要执行下面程序,需要安装Beautiful Soup和requests,具体安装方法请见:https://www.cnblogs.com/xiandedanteng/p/8668492.html # ...

  2. Python 多进程 多线程 协程 I/O多路复用

    引言 在学习Python多进程.多线程之前,先脑补一下如下场景: 说有这么一道题:小红烧水需要10分钟,拖地需要5分钟,洗菜需要5分钟,如果一样一样去干,就是简单的加法,全部做完,需要20分钟:但是, ...

  3. Python编程-多线程

    一.python并发编程之多线程 1.threading模块 multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性,因而不再详细介绍 1.1 开启线程的 ...

  4. Python爬虫 | 多线程、多进程、协程

    对于操作系统来说,一个任务就是一个进程(Process),比如打开一个浏览器就是启动一个浏览器进程,打开一个记事本就启动了一个记事本进程,打开两个记事本就启动了两个记事本进程,打开一个Word就启动了 ...

  5. Python实现多线程HTTP下载器

    本文将介绍使用Python编写多线程HTTP下载器,并生成.exe可执行文件. 环境:windows/Linux + Python2.7.x 单线程 在介绍多线程之前首先介绍单线程.编写单线程的思路为 ...

  6. python的多线程到底有没有用?

    在群里经常听到这样的争执,有人是虚心请教问题,有人就大放厥词因为这个说python辣鸡.而争论的核心无非就是,python的多线程在同一时刻只会有一条线程跑在CPU里面,其他线程都在睡觉.这是真的吗? ...

  7. python面试题(转自https://www.cnblogs.com/wupeiqi/p/9078770.html)

    第一部分 Python基础篇(80题) 为什么学习Python? 通过什么途径学习的Python? Python和Java.PHP.C.C#.C++等其他语言的对比? 简述解释型和编译型编程语言? P ...

  8. python基础===多线程

    https://www.cnblogs.com/wj-1314/p/8263328.html threading 模块 先上代码: import time, threading def loop(): ...

  9. Python之多线程与多进程(一)

    多线程 多线程是程序在同样的上下文中同时运行多条线程的能力.这些线程共享同一个进程的资源,可以在并发模式(单核处理器)或并行模式(多核处理器)下执行多个任务 多线程有以下几个优点: 持续响应:在单线程 ...

随机推荐

  1. 使用CSS进行定位

    CSS中通过使用position属性,有4种不同类型的定位方式,这会影响元素框生成的方式. position属性值的含义: static:静态定位 元素框正常生成.块级元素生成一个矩形框,作为文档流的 ...

  2. 谷歌眼镜能给Apple Watch带来啥前车之鉴?

    当下,你想不听到Apple Watch的消息都难.这款智能手表在三月初发布时,有关它的新闻报道铺天盖地.记者们在博客上对发布会的每个阶段进行了实况报道,苹果粉丝们通过博客. 推特和YouTube视频对 ...

  3. spring jpa和mybatis整合

    spring jpa和mybatis整合 前一阵子接手了一个使用SpringBoot 和spring-data-jpa开发的项目 后期新加入一个小伙伴,表示jpa相比mybatis太难用,多表联合的查 ...

  4. SpringBoot(一)初遇

    环境: IDEA 2018.1.3 , jdk 1.8 , maven 3.3.9 零 第一次接触springboot, 如何学习比较困惑, 思前想后最后决定从文档来学习, 以下为学习中的参考资料: ...

  5. wcf远程服务器返回错误404

    最近根据quartz.net 和wcf做资讯内容定时推送,wcf调用的时候出现远程服务器返回错误404,一直找不到原因是什么,客户端和服务器地址和配置都没啥问题,最后发现wcf请求数据,有传输大小限制 ...

  6. 0<Double.MIN_VALUE

    好吧, 吐嘈一下: 前几天写代码时发现 Double 有几个静态成员变量, 如 MAX_VALUE , MIN_VALUE 等, 当时就自己"故名思意"了, 分别当成了 doubl ...

  7. 转:Jquery如何获取某个元素前(后)的文本内容?

    原文:[解决]Jquery如何获取某个元素前(后)的文本内容? <span> text here... <a id="target_element">百万创 ...

  8. maven 安装下载与配置 代理设置 《解决下载慢问题》

    maven:下载地址http://mirror.bit.edu.cn/apache/maven/maven-3/ 解压之后配置环境 %maven_home%  d:\*****path 中添加 %ma ...

  9. phoenix使用vue

    phoenix使用vue mix phoenix.new ass2 Fetch and install dependencies? [Yn] y 修改 package.json { "rep ...

  10. Pwn with File结构体之利用 vtable 进行 ROP

    前言 本文以 0x00 CTF 2017 的 babyheap 为例介绍下通过修改 vtable 进行 rop 的操作 (:-_- 漏洞分析 首先查看一下程序开启的安全措施 18:07 haclh@u ...