Python 进程和线程的简单例程
在使用python thread的过程中如何关闭线程是一个比较麻烦的事情,我编写了一个简单的例程,通过守护线程的方式结束线程的操作.
- 建立一个进程,并运行
- 在进程中创建一个线程,并设置为守护线程
- 运行线程
- 进程结束
- 线程强制关闭
from logging import StreamHandler
from logging import Formatter
from threading import Thread
from multiprocessing import Process # 导入模块
import time
#
def child_thread(count):
while count:
print("child_thread",count)
count=count+1
time.sleep(1)
# 创建进程
def main_process():
print("main_process start")
count=10
t1 = Thread(target=child_thread, daemon=True, args=(count,))
# t1.daemon = True
t1.start()
while count:
print("main_process",count)
time.sleep(1)
count=count-1
print("main_process end",count)
if __name__ == '__main__':
p = Process(target=main_process, args=())
p.start()