The Python thread creates and terminates the instance code
- 2020-07-21 09:01:17
- OfStack
python is mainly through thread and threading modules to achieve multithreading support.
The thread module of python is the underlying module, while the threading module of python is some encapsulation of thread, which can be used more conveniently. However, python (cpython) cannot make full use of CPU resources due to the existence of GIL, so it is assumed that the full use of multi-core CPU computing power requires the use of multiprocessing module (there will be many problems under Windows).
Suppose you can consider using Stackless Python when you have high requirements for threaded applications. Stackless Python is a modified version of Python with better support for multithreaded programming and support for tasklets. Tasklets are lightweight threads that take a lot more time to switch between threads and consume less resources.
There are two ways to create a new thread through the threading module: one is via ES29en. Thread(Target=executable Method) -- that is, pass a runnable method (or object) to the Thread object; The other is to inherit the threading.Thread definition subclass and override the run() method. Of the other method, the only method with which 1 must be overridden is run(), and can be rewritten as needed. It's worth noting that, to rewrite ___ 40en__ (), the parent class of ___ must be called at line 1 of the function, otherwise the error "AssertionError: Thread. 44en__ () not called" will be triggered.
The Python threading module is different from other languages in that it does not provide a method for terminating threads, and threads started through Python ES52en.Thread () are independent of each other. If thread B is started in thread A, then A and B are threads executing independently of each other. Force terminates thread B at the same time as you want to terminate thread A. An easy way to do this is by calling B.setDaemon (True) from thread A.
The problem with this is that the resources in thread B (open files, transferred data, etc.) may not be released correctly. Therefore, setDaemon() is not a good method, and a more appropriate way is through the Event mechanism. The following program illustrates the difference between the setDaemon() and Event mechanisms for terminating child threads.
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 results are:
-------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()
conclusion
That's it for the Python thread creation and termination instance code. Interested friends can continue to refer to other related topics in this site, if there is any deficiency, welcome to comment out. Thank you for your support!