python中對線程的運行和停止怎么實現


 

 

一、啟動線程

啟動太簡單了,隨便一篇python教程有關多線程的講解都會講到;

二、停止線程

這里分享2種思路,

 

方法1:(親測可用,就是有點繁瑣了) 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import inspect
import ctypes
def _async_raise(tid, exctype):
   """raises the exception, performs cleanup if needed"""
   tid = ctypes.c_long(tid)
   if not inspect.isclass(exctype):
     exctype = type (exctype)
   res = ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, ctypes.py_object(exctype))
   if res = = 0 :
     raise ValueError( "invalid thread id" )
   elif res ! = 1 :
     # """if it returns a number greater than one, you're in trouble,
     # and you should call it again with exc=NULL to revert the effect"""
     ctypes.pythonapi.PyThreadState_SetAsyncExc(tid, None )
     raise SystemError( "PyThreadState_SetAsyncExc failed" )
def stop_thread(thread):
   _async_raise(thread.ident, SystemExit)

定義完上面的2個函數后,如下一樣調用即可

stop_thread(myThread)

 

 

(方法2)(親測可用,就是基本思路,全局變量的使用,python 的基本知識)

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import threading
import time
class MyThread(threading.Thread):
   def __init__( self ):
     threading.Thread.__init__( self )
     self .Flag = True        #停止標志位
     self .Parm = 0         #用來被外部訪問的
   
   
   def run( self ):
     while ( True ):
       if ( not self .Flag):
         break
       else :
         time.sleep( 2 )
   
   def setFlag( self ,parm):     #外部停止線程的操作函數
     self .Flag = parm #boolean
  
   def setParm( self ,parm):     #外部修改內部信息函數
     self .Parm = parm
  
   def getParm( self ):       #外部獲得內部信息函數
     return self .Parm
  
  
if __name__ = = "__main__" :
   testThread = MyThread()
   testThread.setDaemon( True )     #設為保護線程,主進程結束會關閉線程
 
   testThread.start()       #開始線程
 
   time.sleep( 2 )          #主進程休眠 2 秒
   testThread.setFlag( False )   #修改線程運行狀態
   time.sleep( 2 )         
   print (testThread.is_alive())  #查看線程運行狀態

 

1
2
3
4
def __init__( self ):
     self .Flag = True        #停止標志位
     self .Parm = 0         #用來被外部訪問的
     #自行添加參數

 

1
2
3
4
5
def __init__( self ):
     threading.Thread.__init__( self )
     self .Flag = True        #停止標志位
     self .Parm = 0         #用來被外部訪問的
   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM