Python多线程之线程创建和终止
python主要是通过thread和threading这两个模块来实现多线程支持。
python的thread模块是比較底层的模块,python的threading模块是对thread做了一些封装,能够更加方便的被使用。可是python(cpython)因为GIL的存在无法使用threading充分利用CPU资源,假设想充分发挥多核CPU的计算能力须要使用multiprocessing模块(Windows下使用会有诸多问题)。
假设在对线程应用有较高的要求时能够考虑使用Stackless Python来完毕。Stackless Python是Python的一个改动版本号,对多线程编程有更好的支持,提供了对微线程的支持。微线程是轻量级的线程,在多个线程间切换所需的时间很多其它,占用资源也更少。
通过threading模块创建新的线程有两种方法:一种是通过threading.Thread(Target=executable Method)-即传递给Thread对象一个可运行方法(或对象);另外一种是继承threading.Thread定义子类并重写run()方法。另外一种方法中,唯一必须重写的方法是run(),可依据需要决定是否重写__init__()。值得注意的是,若要重写__init__(),父类的__init__()必需要在函数第一行调用,否则会触发错误“AssertionError:
Thread.__init__() not called”
Python threading模块不同于其它语言之处在于它没有提供线程的终止方法,通过Python threading.Thread()启动的线程彼此是独立的。若在线程A中启动了线程B,那么A、B是彼此独立执行的线程。若想终止线程A的同一时候强力终止线程B。一个简单的方法是通过在线程A中调用B.setDaemon(True)实现。
但这样带来的问题是:线程B中的资源(打开的文件、传输数据等)可能会没有正确的释放。所以setDaemon()并不是一个好方法,更为妥当的方式是通过Event机制。以下这段程序体现了setDaemon()和Event机制终止子线程的差别。
import threading
import time
class mythread(threading.Thread):
def __init__(self,stopevt = None,File=None,name = 'subthread',Type ='event'):
threading.Thread.__init__(self)
self.stopevt = stopevt
self.name = name
self.File = File
self.Type = Type def Eventrun(self):
while not self.stopevt.isSet():
print self.name +' alive\n'
time.sleep(2)
if self.File:
print 'close opened file in '+self.name+'\n'
self.File.close()
print self.name +' stoped\n' def Daemonrun(self):
D = mythreadDaemon(self.File)
D.setDaemon(True)
while not self.stopevt.isSet():
print self.name +' alive\n'
time.sleep(2)
print self.name +' stoped\n'
def run(self):
if self.Type == 'event': self.Eventrun()
else: self.Daemonrun()
class mythreadDaemon(threading.Thread):
def __init__(self,File=None,name = 'Daemonthread'):
threading.Thread.__init__(self)
self.name = name
self.File = File
def run(self):
while True:
print self.name +' alive\n'
time.sleep(2)
if self.File:
print 'close opened file in '+self.name+'\n'
self.File.close()
print self.name +' stoped\n' def evtstop():
stopevt = threading.Event()
FileA = open('testA.txt','w')
FileB = open('testB.txt','w')
A = mythread(stopevt,FileA,'subthreadA')
B = mythread(stopevt,FileB,'subthreadB')
print repr(threading.currentThread())+'alive\n'
print FileA.name + ' closed? '+repr(FileA.closed)+'\n'
print FileB.name + ' closed? '+repr(FileB.closed)+'\n'
A.start()
B.start()
time.sleep(1)
print repr(threading.currentThread())+'send stop signal\n'
stopevt.set()
A.join()
B.join()
print repr(threading.currentThread())+'stoped\n'
print 'after A stoped, '+FileA.name + ' closed? '+repr(FileA.closed)+'\n'
print 'after A stoped, '+FileB.name + ' closed? '+repr(FileB.closed)+'\n'
def daemonstop():
stopevt = threading.Event()
FileA = open('testA.txt','r')
A = mythread(stopevt,FileA,'subthreadA',Type = 'Daemon')
print repr(threading.currentThread())+'alive\n'
print FileA.name + ' closed? '+repr(FileA.closed)+'\n'
A.start()
time.sleep(1)
stopevt.set()
A.join()
print repr(threading.currentThread())+'stoped\n'
print 'after A stoped, '+FileA.name + ' closed? '+repr(FileA.closed)+'\n'
if not FileA.closed:
print 'You see the differents, the resource in subthread may not released with setDaemon()'
FileA.close()
if __name__ =='__main__':
print '-------stop subthread example with Event:----------\n'
evtstop()
print '-------Daemon stop subthread example :----------\n'
daemonstop()
执行结果是:
-------stop subthread example with Event:----------
<_MainThread(MainThread, started 2436)>alive
testA.txt closed? False
testB.txt closed? False
subthreadA alive
subthreadB alive <_MainThread(MainThread, started 2436)>send stop signal
close opened file in subthreadA
close opened file in subthreadB subthreadA stoped
subthreadB stoped <_MainThread(MainThread, started 2436)>stoped
after A stoped, testA.txt closed? True
after A stoped, testB.txt closed? True
-------Daemon stop subthread example :----------
<_MainThread(MainThread, started 2436)>alive
testA.txt closed? False
subthreadA alive
subthreadA stoped
<_MainThread(MainThread, started 2436)>stoped
after A stoped, testA.txt closed? False
You see the differents, the resource in subthread may not released with setDaemon()
Python多线程之线程创建和终止的更多相关文章
- Java基础加强之多线程篇(线程创建与终止、互斥、通信、本地变量)
线程创建与终止 线程创建 Thread类与Runnable接口的关系 public interface Runnable { public abstract void run(); } public ...
- Java基础之多线程篇(线程创建与终止、互斥、通信、本地变量)
线程创建与终止 线程创建 Thread类与Runnable接口的关系 public interface Runnable { public abstract void run(); } public ...
- Java基础学习总结(88)——线程创建与终止、互斥、通信、本地变量
线程创建与终止 线程创建 Thread类与 Runnable 接口的关系 public interface Runnable { public abstract void run(); ...
- python多线程与线程
进程与线程的概念 进程 考虑一个场景:浏览器,网易云音乐以及notepad++ 三个软件只能顺序执行是怎样一种场景呢?另外,假如有两个程序A和B,程序A在执行到一半的过程中,需要读取大量的数据输入(I ...
- Python 多线程和线程池
一,前言 进程:是程序,资源集合,进程控制块组成,是最小的资源单位 特点:就对Python而言,可以实现真正的并行效果 缺点:进程切换很容易消耗cpu资源,进程之间的通信相对线程来说比较麻烦 线程:是 ...
- python多线程、线程锁
1.python多线程 多线程可以把空闲时间利用起来 比如有两个进程函数 func1.func2,func1函数里使用sleep休眠一定时间,如果使用单线程调用这两个函数,那么会顺序执行这两个函数 也 ...
- Python多线程、线程池及实际运用
我们在写python爬虫的过程中,对于大量数据的抓取总是希望能获得更高的速度和效率,但由于网络请求的延迟.IO的限制,单线程的运行总是不能让人满意.因此有了多线程.异步协程等技术. 下面介绍一下pyt ...
- linux c学习笔记----线程创建与终止
进程原语 线程原语 描述 fork pthread_create 创建新的控制流 exit pthread_exit 从现有的控制流中退出 waitpid pthread_join 从控制流中得到退出 ...
- 多线程-2.线程创建方式和Thread类
线程的创建方式 1.继承Thread类,重写run方法,示例如下: 1 class PrimeThread extends Thread { 2 long minPrime; 3 PrimeThrea ...
随机推荐
- Bootstrap popover弹出框
popover被挤压.遮挡的问题: 弹出框显示的时候如果贴近一个列的边沿,就会很窄或被遮挡,解决起来很简单,只需在初始化的时候添加一个container属性就可以了: $(function (){ $ ...
- https://leetcode-cn.com/
https://leetcode-cn.com/ 码,马不停蹄,码不停题 英文版:https://leetcode.com/
- (剑指Offer)面试题61:按之字形顺序打印二叉树
题目: 请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推. 思路: 按照广度优先遍历来遍历二叉树,但是需要 ...
- (排序)快速排序QuickSort
主要内容: 1.算法思想 2.快速排序算法 3.划分算法partition 4.快排过程图解 5.完整代码 1.算法思想 快速排序是C.R.A.Hoare于1962年提出的一种划分交换排序.它采用了一 ...
- PHP高级教程-JSON
PHP JSON 本章节我们将为大家介绍如何使用 PHP 语言来编码和解码 JSON 对象. 环境配置 在 php5.2.0 及以上版本已经内置 JSON 扩展. JSON 函数 函数 描述 json ...
- 策略模式(Strategy)简介
一.策略模式(Strategy)简介 策略模式是行为模式. 行为模式:规定了各个对象应该具备的职责以及对象间的通信模式,它很好的规范了对象间调用和数据传递方式 策略模式适合于算法经常变化的情况 算法的 ...
- 有间距的表格布局 table布局
1.先看有间距的布局效果: 2.少说多做,直接看代码(代码中有注释) <!DOCTYPE html> <html lang="zh"> <head&g ...
- uploadify上传之前判断一个input输入框是否为空
onUploadStart:function(file){ if ($("#ContractCode").val() == "") { alert(" ...
- maven org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 60
maven org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant poo ...
- DIV+CSS布局重新学习之float/margin/padding
之前对div的css布局一直有点半知半解,只其然却不知其所以然,到网上下载了“十天学会DIV+CSS(WEB标准)”的chm电子版,然后跟着练习了一下,特在此记录,备忘. <!DOCTYPE h ...