我們都知道,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: ran: 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: ran: 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: 程式設計客棧ran: 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: s')
本文標題: 解決python父執行緒關閉後子執行緒不關閉問題
本文位址:
父頁面開啟子頁面後,子頁面關閉父頁面重新整理
父頁面開啟子頁面後,子頁面關閉父頁面重新整理 下面是很簡單的一種方式,在子頁面重新整理,關閉 window.opener.location.relaod self.close 但是有乙個問題,就是父頁面重新整理的時候有提示框,然後就用了另一種方法 window.opener.refreshdata ...
執行緒關閉 主線程和子執行緒的關閉
今天寫執行緒,再網頁上找了些關閉執行緒的栗子,給大家整理一下 多執行緒程式的開發中,啟動了多個執行緒的程式在關閉的時候卻出現了問題,如果程式退出的時候不關閉執行緒,那麼執行緒就會一直的存在,但是大多啟動的執行緒都是區域性變數,不能一一的關閉,如果呼叫thread.currentthread.abor...
子視窗關閉通知父視窗
子視窗 public partial class formsub form public delegate void updatedatadelegate 宣告乙個委託 public updatedatadelegate updatetextbox 定義委託 public formsub initi...