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线程创建和终止实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

(0)

相关推荐

  • python3+PyQt5 创建多线程网络应用-TCP客户端和TCP服务器实例

    本文在上文的基础上重新实现支持多线程的服务器. 以下为TCP客户端的程序代码: #!/usr/bin/env python3 import sys from PyQt5.QtCore import (QByteArray, QDataStream, QDate, QIODevice, QRegExp, Qt) from PyQt5.QtWidgets import (QApplication, QDateEdit, QFrame, QGridLayout, QHBoxLayout, QLabel

  • python创建线程示例

    复制代码 代码如下: import threadingfrom time import sleep def test_func(id):    for i in range(0,5):        sleep(1)        print('thread %d is running %d' % (id,i)) threads = []for i in range(0,3):    t = threading.Thread(target=test_func, args=(i,))    thr

  • Python基于ThreadingTCPServer创建多线程代理的方法示例

    本文实例讲述了Python基于ThreadingTCPServer创建多线程代理的方法.分享给大家供大家参考,具体如下: #coding=utf8 from BaseHTTPServer import BaseHTTPRequestHandler from SocketServer import ThreadingTCPServer import gzip from StringIO import StringIO import logging logging.basicConfig(level

  • Python使用面向对象方式创建线程实现12306售票系统

    目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更加方便的被使用. 面向对象技术简介 类(Class): 用来描述具有相同的属性和方法的对象的集合.它定义了该集合中每个对象所共有的属性和方法.对象是类的实例. 类变量:类变量在整个实例化的对象中是公用的.类变量定义在类中且在函数体之外.类变量通常不作为实例变量使用. 数据成员:类变量或者实例变量用于

  • Python中多线程的创建及基本调用方法

    1. 多线程的作用 简而言之,多线程是并行处理相互独立的子任务,从而大幅度提高整个任务的效率. 2. Python中的多线程相关模块和方法 Python中提供几个用于多线程编程的模块,包括thread,threading和Queue等 thread模块提供了基本的线程和锁的支持,除产生线程外,也提供基本的同步数据结构锁对象,其中包括: start_new_thread(function, args kwargs=None)  产生一个新的线程来运行给定函数 allocate_lock()  分配

  • 详解Python并发编程之创建多线程的几种方法

    大家好,并发编程 今天开始进入第二篇. 今天的内容会比较基础,主要是为了让新手也能无障碍地阅读,所以还是要再巩固下基础.学完了基础,你们也就能很顺畅地跟着我的思路理解以后的文章. 本文目录 学会使用函数创建多线程 学会使用类创建多线程 多线程:必学函数讲解 经过总结,Python创建多线程主要有如下两种方法: 函数 类 接下来,我们就来揭开多线程的神秘面纱. . 学会使用函数创建多线程 在Python3中,Python提供了一个内置模块 threading.Thread,可以很方便地让我们创建多

  • python线程的几种创建方式详解

    Python3 线程中常用的两个模块为: _thread threading(推荐使用) 使用Thread类创建 import threading from time import sleep,ctime def sing(): for i in range(3): print("正在唱歌...%d"%i) sleep(1) def dance(): for i in range(3): print("正在跳舞...%d"%i) sleep(1) if __name

  • Python线程创建和终止实例代码

    python主要是通过thread和threading这两个模块来实现多线程支持. python的thread模块是比較底层的模块,python的threading模块是对thread做了一些封装,能够更加方便的被使用.可是python(cpython)因为GIL的存在无法使用threading充分利用CPU资源,假设想充分发挥多核CPU的计算能力须要使用multiprocessing模块(Windows下使用会有诸多问题). 假设在对线程应用有较高的要求时能够考虑使用Stackless Pyt

  • Python线程池thread pool创建使用及实例代码分享

    目录 前言 一.线程 1.线程介绍 2.线程特性 轻型实体 独立调度和分派的基本单位 可并发执行 4)共享进程资源 二.线程池 三.线程池的设计思路 四.Python线程池构建 1.构建思路 2.实现库功能函数 ThreadPoolExecutor() submit() result() cancel() cancelled() running() as_completed() map() 前言 首先线程和线程池不管在哪个语言里面,理论都是通用的.对于开发来说,解决高并发问题离不开对多个线程处理

  • 使用Python操作excel文件的实例代码

    使用的类库 pip install openpyxl 操作实现 •工作簿操作 # coding: utf-8 from openpyxl import Workbook # 创建一个excel工作簿 wb = Workbook() # 打开一个工作簿 wb = load_workbook('test.xlsx') # 保存工作簿到文件 wb.save('save.xlsx') •工作表操作 # 获得当前的工作表对象 ws = wb.active # 通过工作表名称得到工作表对象 ws = wb.

  • Python实现七彩蟒蛇绘制实例代码

    本文主要研究的是Python编程turtle的实例,绘制一个七彩蟒蛇..具体如下. 第2周的课后练习里,有一道题目,要求修改"蟒蛇绘制"程序,对Python 蟒蛇的每个部分采用不同颜色,绘制一条彩色蟒蛇. 原蟒蛇绘制程序如下: 因为刚开始学Python,不太熟悉,所以自己加了一些注释,方便理解. #蟒蛇绘制 import turtle def drawSnake(rad,angle,len,neckrad): for i in range(len): turtle.circle(rad

  • python3.6连接MySQL和表的创建与删除实例代码

    python3.6不支持importMySQLdb改用为importpymysql模块,需要自行安装模块pymysql. 1:python3.6安装模块pymysql 命令行安装pipinstallpymysql 2:python3.6连接mysql数据库 #!/bin/env Python # -*- coding:utf-8 -*- import pymysql conn = pymysql.connect( user="root", password="root@123

  • Python3之手动创建迭代器的实例代码

    迭代器即可以遍历诸如列表,字典及字符串等序列对象甚至自定义对象的对象,其本质就是记录迭代对象中每个元素的位置.迭代过程从第一个元素至最后一个元素,且过程不能回滚或反方向迭代. 两个基本方法iter.next 序列对象可以利用 iter() 直接创建迭代器,并通过 next() 即可迭代迭代器. 利用for循环迭代 S = 'PYTHON' IT = iter(S) for it in IT: print(it) 示例结果: P Y T H O N 利用next()迭代 S = 'PYTHON'

  • python读写Excel表格的实例代码(简单实用)

    安装两个库:pip install xlrd.pip install xlwt 1.python读excel--xlrd 2.python写excel--xlwt 1.读excel数据,包括日期等数据 #coding=utf-8 import xlrd import datetime from datetime import date def read_excel(): #打开文件 wb = xlrd.open_workbook(r'test.xlsx') #获取所有sheet的名字 print

  • Python 实现劳拉游戏的实例代码(四连环、重力四子棋)

    游戏规则:双方轮流选择棋盘的列号放进自己的棋子, 若棋盘上有四颗相同型号的棋子在一行.一列或一条斜线上连接起来, 则使用该型号棋子的玩家就赢了! 程序实现游戏,并将每局的数据保存到本地的文件中 首先我们要创建一个空白的棋盘 def into():#初始空白棋盘 for i in range(6): list_width=[] for j in range(8): list_width.append(' '+'|') screen.append(list_width) 然后呢 我们再写一个输赢判断

  • 用python生成一张壁纸实例代码

    目录 前言 代码 效果 总结 前言 之前在csdn上看见用python写春联的,这次突发奇想用python制作一张壁纸,其元素包括背景.文字.图片. 知识点 用PIL创建一张纯色背景Image.new:图片上添加文字ImageDraw,cv2只能显示英文:转换图片的透明度:图片上叠加图片:jpg与png的区别. 代码 import os from PIL import ImageFont, ImageDraw, Image import cv2 import random def white2t

  • MyBatis创建存储过程的实例代码_动力节点Java学院整理

    所需要用到的其他工具或技术: 项目管理工具 : Maven 测试运行工具 : Junit 数据库 : Derby 本节需要用到的有2部分,第一部分是如何在Derby中创建存储过程,第二部分是如何在Mybatis中调用存储过程 一. 在Derby中创建存储过程 在Eclipse中创建一个新的普通Java项目命名为Test_Store_Procedure 在com.bjpowernode.practice包下创建一个Class命名为StoreProcedureOperationClass.class

随机推荐