1. 程式人生 > 程式設計 >解決python父執行緒關閉後子執行緒不關閉問題

解決python父執行緒關閉後子執行緒不關閉問題

我們都知道,python可以通過threading module來建立新的執行緒,然而在建立執行緒的執行緒(父執行緒)關閉之後,相應的子執行緒可能卻沒有關閉,這可能是因為程式碼中沒有使用setDaemon(True)函式。

接下來,使用一個例子來說明:

import threading

def prt_hello() :
  while 1 :
    print 'hello'

if __name__ == '__main__' :
  t = threading.Thread(target=prt_hello)
  t.setDaemon(True)
  t.start()

我們需要把setDaemon函式放在start函式前面,不然它是不給通過的,並且返回'cannot set daemon status of active thread‘

補充知識:Python 多執行緒的退出/停止的一種是實現思路

在使用多執行緒的過程中,我們知道,python的執行緒是沒有stop/terminate方法的,也就是說它被啟動後,你無法再主動去退出它,除非主程序退出了,注意,是主程序,不是執行緒的父程序.

一個比較合理的方式就是把原因需要放到threading.Thread的target中的執行緒函式,改寫到一個繼承類中,下面是一個實現例子

import threading
import time
import os
 
# 原本需要用來啟動的無線迴圈的函式
def print_thread():
  pid = os.getpid()
  counts = 0
  while True:
    print(f'threading pid: {pid} ran: {counts:04d} s')
    counts += 1
    time.sleep(1)
 
# 把函式放到改寫到類的run方法中,便可以通過呼叫類方法,實現執行緒的終止
class StoppableThread(threading.Thread):
 
  def __init__(self,daemon=None):
    super(StoppableThread,self).__init__(daemon=daemon)
    self.__is_running = True
    self.daemon = daemon
 
  def terminate(self):
    self.__is_running = False
 
  def run(self):
    pid = os.getpid()
    counts = 0
    while self.__is_running:
      print(f'threading running: {pid} ran: {counts:04d} s')
      counts += 1
      time.sleep(1)
 
 
def call_thread():
  thread = StoppableThread()
  thread.daemon = True
  thread.start()
 
  pid = os.getpid()
  counts = 0
  for i in range(5):
    print(f'0 call threading pid: {pid} ran: {counts:04d} s')
    counts += 2
    time.sleep(2)
  # 主動把執行緒退出
  thread.terminate()
 
 
if __name__ == '__main__':
  call_thread()
  print(f'==========call_thread finish===========')
  counts = 0
  for i in range(5):
    counts += 1
    time.sleep(1)
    print(f'main thread:{counts:04d} s')

以上這篇解決python父執行緒關閉後子執行緒不關閉問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。