Python中的线程threading对象

本文详细介绍了Python中的线程threading对象,包括Thread类的使用,线程的启动与退出,线程安全,daemon线程和non-daemon线程的概念及应用场景,以及threading.local类在多线程中的作用域管理。
摘要由CSDN通过智能技术生成

Python中的线程threading对象

Python的线程开发使用标准库threading
进程靠线程执行代码,至少有一个主线程,其它线程是工作线程。
主线程是第一个启动的线程。
父线程:如果线程A中启动了一个线程B,A就是B的父线程。
子线程:B就是A的子线程。

Thread类

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None) #线程

# 签名 
def __init__(self, group=None, target=None, name=None,args=(), kwargs=None, *, daemon=None)
    pass
参数名 含义
target 线程调用的对象,就是目标函数
name 为线程起一个名字(线程的名字)
args 为目标函数传递实参,元组
kwargs 为目标函数传递关键字参数,字典

线程并启动与退出

  • 通过threading.Thread创建一个线程对象,target是目标函数,可以使用name为线程指定名称。
  • 启动线程需要调用线程的start()方法才能启动
  • 线程之所以执行函数,是因为线程中就是要执行代码的,而简单的封装就是函数,所以还是函数调用
  • 线程执行完,线程就退出了
  • Python没有提供线程退出的方法,线程在下面情况时退出
    1. 线程函数内语句执行完毕
    2. 线程函数中抛出未处理的异常
  • Python的线程没有优先级、没有线程组的概念,也不能被销毁、停止、挂起,那也就没有恢复、中断了。
import threading

def worker():
    print("hello word")
    print("my name is xdd")

t = threading.Thread(target=worker,name="xdd") #创建一个线程对象
t.start() #启动线程

def add(x,y):
    print("{} + {} = {}".format(x,y,x+y),threading.current_thread().ident)

tt = threading.Thread(target=add,name="xddadd",args=(3,),kwargs={
   "y":15})
tt.start()

threading_002

threading的属性和方法

名称 含义
threading.current_thread() 返回当前线程对象
threading.current_thread().ident 返回当前线程的id
threading.main_thread() 返回主线程(main线程)对象
threading.active_count() 返回当前处于active状态的线程个数。(活着的,还未运行结束的线程个数)
threading.enumerate() 返回所有活着的线程列表,不包括已经终止的线程和未开始的线程
threading.getident() 返回当前线程的ID,非0整数
  • active_count,enumerate方法返回的值包含主线程。
import threading

def shothread():
    print("- "*30)
    print(threading.enumerate())
    print(threading.active_count())
    print(threading.get_ident())
    print(threading.current_thread(),threading.current_thread().ident)
    print(threading.main_thread())

shothread()
t = threading.Thread(target=shothread)
t.start()

threading_003

Thread线程的实例对象的属性和方法

名称 含义
Thread.name 线程的名字,一个标识符,线程的名称可以重名。getName(),setNa
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值