Python线程join和setDaemon
生活随笔
收集整理的這篇文章主要介紹了
Python线程join和setDaemon
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
看一下線程的setDaemon()方法
import time import threading import ctypes import inspectdef sayHello():for i in range(10):print("hello")time.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.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)if __name__ == '__main__':# sayHello()t = threading.Thread(target=sayHello, args=())t.setDaemon(True) # 主線程結束后停止子線程t.start()for i in range(3):print(t.is_alive())time.sleep(1)上面的輸出是:
hello True True hello hello True hello我們修改一下代碼:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import time import threading import ctypes import inspectdef sayHello():for i in range(10):print("hello")time.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.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)if __name__ == '__main__':# sayHello()t = threading.Thread(target=sayHello, args=())t.setDaemon(False) # 主線程結束后不停止子線程t.start()for i in range(3):print(t.is_alive())time.sleep(1)程序的輸出是:
hello True True hello hello True hello hello hello hello hello hello hello可見,setDaemon()方法就是決定在主線程結束后是否結束子線程,如果為True時,會結束子線程,為False時,不會結束子線程。
我們再來看join()方法:
直接看代碼
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import time import threading import ctypes import inspectdef sayHello():for i in range(10):print("hello")time.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.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)if __name__ == '__main__':# sayHello()t = threading.Thread(target=sayHello, args=())t.setDaemon(False) # 主線程結束后不停止子線程t.start()for i in range(3):print(t.is_alive())time.sleep(1)# t.join()print("over")輸出結果為:
hello True True hello True hello hello over hello hello hello hello hello hello可以看到主線程結束時,打印出over,之后子線程還在繼續打印hello
修改代碼:
''' 遇到問題沒人解答?小編創建了一個Python學習交流QQ群:778463939 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import time import threading import ctypes import inspectdef sayHello():for i in range(10):print("hello")time.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.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)if __name__ == '__main__':# sayHello()t = threading.Thread(target=sayHello, args=())t.setDaemon(False) # 主線程結束后不停止子線程t.start()for i in range(3):print(t.is_alive())time.sleep(1)t.join()print("over")輸出結果為:
hello True hello True True hello hello hello hello hello hello hello hello over可以看到設置t.join()方法之后,主線程要等待t這個線程結束之后,才能繼續,也就是等hello打印完之后才打印over。
總結
以上是生活随笔為你收集整理的Python线程join和setDaemon的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python with语句与contex
- 下一篇: 3种python调用其他脚本的方法,你还