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

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

单线程

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

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

from time import ctime,sleep

def music():
for i in range(2):
print "I was listening to music. %s" %ctime()
sleep(1) def move():
for i in range(2):
print "I was at the movies! %s" %ctime()
sleep(5) if __name__ == '__main__':
music()
move()
print "all over %s" %ctime()

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

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

print "all over %s" %ctime()

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

运行结果:

>>=========================== RESTART ================================
>>>
I was listening to music. Thu Apr 17 10:47:08 2014
I was listening to music. Thu Apr 17 10:47:09 2014
I was at the movies! Thu Apr 17 10:47:10 2014
I was at the movies! Thu Apr 17 10:47:15 2014
all over Thu Apr 17 10:47:20 2014

  

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

#coding=utf-8
import threading
from time import ctime,sleep def music(func):
for i in range(2):
print "I was listening to %s. %s" %(func,ctime())
sleep(1) def move(func):
for i in range(2):
print "I was at the %s! %s" %(func,ctime())
sleep(5) if __name__ == '__main__':
music(u'爱情买卖')
move(u'阿凡达') print "all over %s" %ctime()

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

运行结果:

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

多线程

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

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

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

#coding=utf-8
import threading
from time import ctime,sleep def music(func):
for i in range(2):
print "I was listening to %s. %s" %(func,ctime())
sleep(1) def move(func):
for i in range(2):
print "I was at the %s! %s" %(func,ctime())
sleep(5) threads = []
t1 = threading.Thread(target=music,args=(u'爱情买卖',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'阿凡达',))
threads.append(t2) if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start() 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()

开始线程活动。

运行结果:

>>> ========================= RESTART ================================
>>>
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())都是同一时间启动,但由于主线程执行完结束,所以导致子线程也终止。

继续调整程序:

...
if __name__ == '__main__':
for t in threads:
t.setDaemon(True)
t.start() t.join() print "all over %s" %ctime()

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

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

运行结果:

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

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

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

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

执行结果:

>>> ====================== RESTART ================================
>>>
I was listening to 爱情买卖. Thu Apr 17 13:11:27 2014I was at the 阿凡达! Thu Apr 17 13:11:27 2014 I was listening to 爱情买卖. Thu Apr 17 13:11:31 2014
I was at the 阿凡达! Thu Apr 17 13:11:32 2014
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. [转]C#进阶系列——WebApi 接口参数不再困惑:传参详解

    本文转自:http://www.cnblogs.com/landeanfen/p/5337072.html#_label1_2 阅读目录 一.get请求 1.基础类型参数 2.实体作为参数 3.数组作 ...

  2. 我所了解的Hibernate注解

    一,首先需要导入支持注解开发的jar包: hibernate-annotations.jar hibernate-commons-annotations.jar (Hibernate中支持注解开发的j ...

  3. CSS3完善和模式

    CSS3改善了传统盒模型架构,增强盒子构成要素的功能,扩展了盒模型显示的方式,具体描述如下 改善构造:除了传统的内容区域,边框区,补白区和边界区外,为盒子新增了轮廓区. 增强功能:内容增强CSS自动添 ...

  4. ffmpeg按比例缩放--"width / height not divisible by 2" 解决方法

    最近在处理视频的时候,有这么一个需求 如果视频的分辨率宽度大于960的话,就把宽度设为960,而高度按其比例进行缩放 如果视频的分辨率高度大于540的话,就把高度设为540,而宽度按其比例进行缩放 之 ...

  5. Java Swing实战(一)JFrame和JTabbedPane容器

    概述: 项目是一个桌面程序,涉及标签和按钮组件.布局管理器组件.面板组件.列表框和下拉框组件等组件,以及Swing事件处理机制. 下面先从最基础的界面开始. /** * @author: lishua ...

  6. nginx 错误日志分析

    502 1.查看nginx错误日志 tailf /data/log/nginx/error.log // :: [error] #: * recv() failed (: Connection res ...

  7. spring cloud 服务发现

    Eureka 当注册中心使用. 注: 1.当仅有一台Eureka时,不需要向别的节点注册. 2.集群的时候,需要相互注册. 工作方式: 前提: Eureka    //注册中心 provide1  / ...

  8. Unix Programming :文件IO

    文件描述符常量(unistd.h): STDIN_FILENO STDOUT_FILENO STDERR_FILENO 通常这些常量分别对应于数字0,1,2 文件操作需要头文件 fcntl.h ,一些 ...

  9. confirm(message)

    如果用户点击确定按钮,则 confirm() 返回 true.如果点击取消按钮,则 confirm() 返回 false. 在用户点击确定按钮或取消按钮把对话框关闭之前,它将阻止用户对浏览器的所有输入 ...

  10. HackerRank Special Substrings 回文树+后缀自动机+set

    传送门 既然要求对每个前缀都求出答案,不难想到应该用回文树求出所有本质不同的回文子串. 然后考虑如何对这些回文子串的前缀进行去重. 结论:答案等于所有本质不同的回文子串长之和减去字典序相邻的回文子串的 ...