虫师 python_python 多线程就这么简单 - 虫师
多线程和多进程是什么自行 google
补脑
对于 python
多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂。所以,这里力图用简单的例子,让你对多线程有个初步的认识。
单线程
在好些年前的 MS-DOS
时代,操作系统处理问题都是单任务的,我想做听音乐和看电影两件事儿,那么一定要先排一下顺序。
(好吧!我们不纠结在
DOS
时代是否有听音乐和看影的应用。
^_^
)
from time importctime,sleepdefmusic():for i in range(2):print "I was listening to music. %s" %ctime()
sleep(1)defmove():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循环看两遍。在整个休闲娱乐活动结束后,我看了一下当前时间,差不多该睡觉了。
运行结果:
>>=========================== RESTART ================================
>>>I was listening to music. Thu Apr17 10:47:08 2014I was listening to music. Thu Apr17 10:47:09 2014I was at the movies! Thu Apr17 10:47:10 2014I was at the movies! Thu Apr17 10:47:15 2014all over Thu Apr17 10:47:20 2014
其实,music()和move()更应该被看作是音乐和视频播放器,至于要播放什么歌曲和视频应该由我们使用时决定。所以,对上面代码做了改造:
#coding=utf-8
importthreadingfrom time importctime,sleepdefmusic(func):for i in range(2):print "I was listening to %s. %s" %(func,ctime())
sleep(1)defmove(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 Apr1711:48:59 2014I was listening to 爱情买卖. Thu Apr17 11:49:00 2014I was at the 阿凡达! Thu Apr17 11:49:01 2014I was at the 阿凡达! Thu Apr17 11:49:06 2014all over Thu Apr1711:49:11 2014
多线程
科技在发展,时代在进步,我们的CPU也越来越快,CPU抱怨,P大点事儿占了我一定的时间,其实我同时干多个活都没问题的;于是,操作系
统就进入了多任务时代。我们听着音乐吃着火锅的不在是梦想。
python提供了两个模块来实现多线程thread 和threading ,thread 有一些缺点,在threading 得到了弥补,为了不浪费你和时间,所以我们直
接学习threading 就可以了。
继续对上面的例子进行改造,引入threadring来同时播放音乐和视频:
#coding=utf-8
importthreadingfrom time importctime,sleepdefmusic(func):for i in range(2):print "I was listening to %s. %s" %(func,ctime())
sleep(1)defmove(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 inthreads:
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循环遍历数组。
setDaemon()
setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线
程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。
start()
开始线程活动。
运行结果:
>>> ========================= RESTART ================================
>>>I was listening to 爱情买卖. Thu Apr17 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 inthreads:
t.setDaemon(True)
t.start()
t.join()print "all over %s" %ctime()
我们只对上面的程序加了个join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直被阻塞。
注意:
join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。
运行结果:
>>> ========================= RESTART ================================
>>>I was listening to 爱情买卖. Thu Apr17 13:04:11 2014 I was at the 阿凡达! Thu Apr 17 13:04:11 2014I was listening to 爱情买卖. Thu Apr17 13:04:12 2014I was at the 阿凡达! Thu Apr17 13:04:16 2014all over Thu Apr1713:04:21 2014
从执行结果可看到,music 和move 是同时启动的。
开始时间4分11秒,直到调用主进程为4分22秒,总耗时为10秒。从单线程时减少了2秒,我们可以把music的sleep()的时间调整为4秒。
...defmusic(func):for i in range(2):print "I was listening to %s. %s" %(func,ctime())
sleep(4)
...
执行结果:
>>> ====================== RESTART ================================
>>>I was listening to 爱情买卖. Thu Apr17 13:11:27 2014I was at the 阿凡达! Thu Apr 17 13:11:27 2014I was listening to 爱情买卖. Thu Apr17 13:11:31 2014I was at the 阿凡达! Thu Apr17 13:11:32 2014all over Thu Apr17 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_python 多线程就这么简单 - 虫师相关推荐
- python 多线程就这么简单(续)
python 多线程就这么简单(续) 之前讲了多线程的一篇博客,感觉讲的意犹未尽,其实,多线程非常有意思.因为我们在使用电脑的过程中无时无刻都在多进程和多线程.我们可以接着之前的例子继续讲.请先看我的 ...
- python 多线程就这么简单
python 多线程就这么简单 多线程和多进程是什么自行google补脑 对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用简单的例子,让你对多线程有个初 ...
- 虫师 python_python学习虫师笔记 (一)
虫师博客:http://www.cnblogs.com/fnng/p/3576154.html 我的笔记 初期:一开始学习python是通过看书 第一本python的书叫<python核心编程& ...
- multiprocessing python_Python多线程/进程(threading、multiprocessing)知识覆盖详解
你好,我是goldsunC 让我们一起进步吧! 基本知识 在Python中有一个全局解释器锁GIL(Global Interpreter Lock).GIL源于Python设计之初的考虑,目的是使数据 ...
- python多线程并发写入_Python多线程并发的简单测试
之前也写了一些简单的Python程序,对于多线程的并发一直没有涉及,今天决定先突破一下,把这个部分的内容先快速的掌握,然后在这个基础上细化改进. 我的好友冰川擅长Python技术,所以就拿来主义,参考 ...
- Linux多线程实践(9) --简单线程池的设计与实现
线程池的技术背景 在面向对象编程中,创建和销毁对象是很费时间的,因为创建一个对象要获取内存资源或者其它更多资源.在Java中更是如此,虚拟机将试图跟踪每一个对象,以便能够在对象销毁后进行垃圾回收.所以 ...
- python技术简介_Python多线程技术简介,简单,阐述,python
python多线程 python中创建多线程方法有两种,这里只介绍简单的一种: from threading import Thread #导入模块 import time def test(thre ...
- 使用qt多线程的一个简单方法
有时候在gui编程中需要调用一个非常耗费时间的api类的函数,这个时候不使用多线程的话界面就会卡死.使用多线程有一个非常简单的办法,不需要建立新的QThread派生类. 设需要调用的api定义为 bo ...
- java 多线程 从无到有_多线程断点续传(简单demo)——从无到有
复杂功能总是由许多小功能组合在一起完成的,一步一步完成多线程断点续传,可以从以下几个方面来考虑. 第一,实现简单的下载: 第二,打断下载线程,实现暂停功能: 第三,从已经下载点进行续传: 第四,引入多 ...
最新文章
- 迪克森沉思录之做Global SAP项目的弊端
- XamarinEssentials教程获取首选项的值
- SQLite3动态创建表
- IOS开发之__bridge,__bridge_transfer和__bridge_retained
- linux挂载磁盘分区,Linux 新磁盘分区与挂载
- htm怎么让图片和搜索框在同一行_新手怎么玩好小红书
- qgis在地图上画导航线_在Laravel中的航线
- screentogif 屏幕录制生成gif图片的软件安装过程
- springboot整合通用mapper操作数据库
- 从Android上的相机裁剪图像
- Linux NTP时间服务器搭建
- java 数组有序_Java有序数组
- 计算机发展史的第五个阶段,信息技术的发展历程是怎样的? 信息技术的发展历程分五个阶段...
- C# - [实践] 电子词典
- 目标定位和检测系列中IOU的含义
- JS项目获取pc mac地址
- uniapp 使用微信扫一扫功能扫描指定二维码查看返回值
- STM32开发项目:定时器预装载寄存器(ARR)
- Effective-Java 谨慎使用流并行
- 决策树算法的 MATLAB 实践