Skip to content

Instantly share code, notes, and snippets.

@xiazhibin
Last active April 12, 2018 08:25
Show Gist options
  • Save xiazhibin/80d115d455bcb90bf5fc012b626e82d7 to your computer and use it in GitHub Desktop.
Save xiazhibin/80d115d455bcb90bf5fc012b626e82d7 to your computer and use it in GitHub Desktop.
线程一些常识

主线程退出对子线程的影响

进程是资源分配的基本单位,线程是CPU调度的基本单位

Main线程是个非守护线程,不能设置成守护线程

import threading
import time

threading.currentThread().setDaemon(True)
time.sleep(1)
print('main thread end')

RuntimeError: cannot set daemon status of active thread

Main线程结束,其他线程一样可以正常运行

import threading
import time
import os

def func():
    time.sleep(5)
    print("child thread finish")

threading.Thread(target=func).start()
print("main thread exit")

Main线程结束,其他线程也可以立刻结束如果这些子线程都是守护线程。

import threading
import time


def func():
    time.sleep(3)
    print('child thread exit')


t = threading.Thread(target=func)
t.setDaemon(True)
t.start()
print('main thread exit')

进程结束,任何线程都结束

import threading
import time
import os


def func():
    time.sleep(3)
    print('child thread exit')


t = threading.Thread(target=func)
t.start()
os._exit(-1)
print('main thread exit')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment