Create and terminate multiple threads in Python and multiple threads in python

Source: Internet
Author: User

Create and terminate multiple threads in Python and multiple threads in python

Python supports multiple threads through the thread and threading modules. The thread module of python is a relatively low-level module, and the threading module of python encapsulates the thread and can be used more conveniently. However, due to the existence of GIL, python (cpython) cannot use threading to make full use of CPU resources. To make full use of the computing power of multi-core CPUs, you need to use the multiprocessing module (which may cause many problems in Windows ).

If you have high requirements on thread applications, you can use Stackless Python. Stackless Python is a modified version of Python that provides better support for multi-threaded programming and supports micro-threads. A micro-thread is a lightweight thread. It takes more 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)-an executable Method (or object) that is passed to the Thread object. The second Method inherits threading. thread defines subclass and overwrites the run () method. In the second 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 through Python threading. threads () are independent of each other. If Thread B is started in Thread A, threads A and B run independently of each other. To terminate thread A while strongly terminating 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, data transmission, 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 demonstrates the difference between 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 running 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()  



A multi-threaded program written in python executes the thread created by multiple threads cyclically. However, after the program is executed for a certain period of time

It seems that your fifth thread is suspended, which makes it impossible to release the lock resource.

A newbie to Python Multithreading

Use the join function of the threading module to check whether the thread is finished.
If you can only use the thread module, you can use the flag, but the efficiency is relatively low and the code style is not good.
This is equivalent to a spin lock.
From time import sleep, ctimeimport threaddef loop0 (sign): print 'start loop 0 at: ', ctime () sleep (4) print 'loop 0 done at:', ctime () sign [0] = True def loop1 (sign): print 'start loop 1 at: ', ctime () sleep (2) print 'loop 1 done at:', ctime () sign [1] = True def main (): print 'starting at: ', ctime () sign = [False, False] thread. start_new_thread (loop0, (sign,) thread. start_new_thread (loop1, (sign,) while not all (sign): pass print 'all DONE at: ', ctime () if _ name __= = '_ main _': main ()

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.