Python多线程

主线程与子线程

创建子线程child_thread和父线程parent_thread,默认创建的子线程都不是守护线程(setDaemon默认值为False)

import threading
import time

def child_thread():
    for i in range(5):
        time.sleep(1)
        print(f"child thread {i}")


def parent_thread():
    print("parent thread start")
    thread = threading.Thread(target=child_thread)
    thread.start()
    print("parent thread end")

parent_thread()

运行结果:

parent thread start
parent thread end
child thread 0
child thread 1
child thread 2
child thread 3
child thread 4

可见父线程运行完成后子线程依然在运行,等待子线程运行完成后进程才会结束。

守护线程

守护线程会在主线程代码执行结束后就终止

def child_thread():
    for i in range(5):
        time.sleep(1)
        print(f"child thread {i}")


def parent_thread():
    print("parent thread start")
    thread = threading.Thread(target=child_thread)
    thread.setDaemon(True) # 设置子线程为守护线程,必须在start()方法前设置
    thread.start()
    print("parent thread end")

parent_thread()

运行结果:

parent thread start
parent thread end

实际上子线程运行了time.sleep(1)

阻塞线程

def child_thread():
    for i in range(5):
        time.sleep(1)
        print(f"child thread {i}")


def parent_thread():
    print("parent thread start")
    thread = threading.Thread(target=child_thread)
    thread.setDaemon(True)
    thread.start()
    thread.join() # 必须在start()方法后设置
    print("parent thread end")

parent_thread()

运行结果:

parent thread start
child thread 0
child thread 1
child thread 2
child thread 3
child thread 4
parent thread end

结果可见,子线程运行完成之前,主线程一直处于阻塞状态,直到子线程运行完成,主线程才会运行完成

守护线程与非守护线程并行

def child_thread1():
    for i in range(5): # thread1循环运行5次
        time.sleep(1)
        print(f"child thread1 {i}")

def child_thread2():
    for i in range(3): # thread2循环运行3次,运行时间少于thread1
        time.sleep(1)
        print(f"child thread2 {i}")

def parent_thread():
    print("parent thread start")
    thread1 = threading.Thread(target=child_thread1)
    thread2 = threading.Thread(target=child_thread2)
    thread1.setDaemon(True) # thread1为守护线程,thread2为非守护线程
    thread1.start()
    thread2.start()

    print("parent thread end")

parent_thread()

运行结果:

parent thread start
parent thread end
child thread2 0child thread1 0

child thread2 1child thread1 1

child thread1 2child thread2 2

可见子线程thread2运行完成后,主线程结束,没有继续运行thread1

posted @ 2021-03-10 11:46  Ravenna  阅读(75)  评论(0编辑  收藏  举报