The Python thread creates and terminates the instance code. The python thread terminates the instance.

Source: Internet
Author: User

The Python thread creates and terminates the instance code. The python thread terminates the instance.

Python supports multiple threads through the thread and threading modules.

The thread module of python is a lower-layer module than the threading module. The threading module of python encapsulates the thread and can be used more conveniently. However, python (cpython) cannot use threading to make full use of CPU resources because of GIL. to make full use of the computing power of multi-core CPUs, you must use the multiprocessing module (which may cause many problems in Windows ).

It is assumed that Stackless Python can be used for thread applications with high requirements. Stackless Python is a Python version that provides better support for multi-threaded programming and supports micro-threads. A micro-thread is a lightweight thread. It takes a lot of time to switch between multiple threads and consumes less resources.

There are two ways to create a new thread through the threading module: One is through threading. thread (Target = executable Method)-that is, a runable Method (or object) is passed to the Thread object, and threading is inherited. thread defines subclass and overwrites the run () method. In another method, the only method that must be overwritten is run (). You can decide whether to rewrite _ init _ () as needed __(). It is worth noting that to override _ init _ (), the _ init _ () of the parent class must be called in the first line of the function, otherwise, the error "AssertionError: Thread. _ init _ () not called"

The Python threading module is different from other languages in that it does not provide a Thread termination method. threads started through Python threading. Thread () are independent of each other. If thread B is started in thread A, threads A and B are executed independently of each other. If you want to terminate thread A at the same time, force terminate thread B. A simple method is to call B. setDaemon (True) in thread.

But the problem is that the resources in thread B (opened files, transmitted data, etc.) may not be correctly released. Therefore, setDaemon () is not a good method. The more appropriate method is to use the Event mechanism. The following program shows the difference between the setDaemon () and the Event mechanism to end the subthread.

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() 

The execution result is:

-------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() 

Summary

The above is all about the Python thread code for creating and terminating instances. I hope it will be helpful to you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.