Python的子執行緒和子程序是如何手動結束的

2022-09-25 10:33:11 字數 2506 閱讀 2769

結束子執行緒的方法:

這個是搬運其他大神的**,鄙人也不知道原理,反正拿來主義,暫時沒發現什麼缺點,先用著再說。

import inspect

import ctypes

import threading

from time import sleep

def serial_read():

while true:

print("春哥純爺們!")

sleep(1)

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.pyt程式設計客棧honapi.pythreadstate_setasyncexc(tiwww.cppcns.comd, 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)

def air():

ords=0

mythread = threading.thread(target=serial_read)

mythread.start()

while true:

ords+=1

if ords==10:

stop_thread(mythread)

print("停止子執行緒")

break

sleep(1)

if __name__ == '__main__':

air()

下面是結束子程序的方法:

import inspect

import ctypes

from time import sleep

from multiprocessing import process

def serial_read():

while true:

print("春哥純爺們!")

sleep(1)

def air():

ords=0

mythread = process(target=serial_read)

mythread.start()

while true:

ords+=1

if ords==10:

mythread.terminate()

print("停止子程序")

break

sleep(1)

if __name__ == '_程式設計客棧_main__':

air()

這裡說一下如果用類的話要如何寫,想結束子程序或者子執行緒就需要拿到程序物件或者執行緒物件,但是類中沒辦法實現建立乙個類屬性的方式然後用self.的方式來在其他類方法中呼叫,這時候就建立乙個類屬性list,然後建立好子程序或者子執行緒後把物件賦值給這個list,再在類的其他方法中呼叫這個list中的元素,就拿到了子程序或者子執行緒的物件了。

例如:def startss(self,a1,b1,c1,under,rough,blue,among):

# 建立新執行緒

p1=threading.thread(target=self.line01,args=(a1,b1,under,rough,)) #必須加,號

p2=threading.thread(target=self.line02,args=(a1,c1,under,blue,))

p3=process(target=self.process01,args=(under,rough,blue,)) #計算程序

#among是類屬性list容器

among.append(p1)

among.append(p2)

among.append(p3)

# 開啟新執行緒

p1.start()

p2.start()

#開啟計算用程序

p3.start()

python 多程序如何終止或重啟子程序

子程序和執行緒

子程序和原來的父程序是相互獨立的,所佔的空間也是相互獨立的,子程序可以讀寫父程序中開啟的檔案,上面鏈結中給出的例子,ie開啟了adobe讀取pdf檔案,認為ie是父程序,adobe是子程序,並且兩者關聯不大。程序和執行緒的區別在於粒度不同,程序之間的變數 或者說是記憶體 是不能直接互相訪問的,而執行...

子執行緒和子程序的建立速度

from threading import thread from mutlprocessing import process import time def task name print f is running time.sleep 2 print f is end if name main ...

主線程和子執行緒

子執行緒通過 handlerthread的thread.getlooper 繫結,在主線程的handler的handlermessage中呼叫threadhandler.sendmessagedelay msg,1000 向子執行緒傳送訊息。在子執行緒中通過handler.sendmessagede...