python多线程模块threading学习总结

本文总结了Python的threading模块,包括active_count、Condition、current_thread、Event、local、Lock、RLock、Thread、Timer等核心概念,并通过示例介绍了线程的创建、启动、同步和管理,以及如何设置守护线程和信号量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

python除了thread模块,提供了更高级的threading模块来实现多线程
另外python在多核cpu中为提高并发,提供了multiprocessing多进程

threading模块提供的方法:

1.threading.active_count()
1.threading.activeCount() 获取正在运行的线程数量

2.threading.Condition() 相当于高级锁对象,可以使一个或多个线程等待直到被其他线程调度或通知, <<详情参考>>

3.threading.current_thread()
3.threading.currentThread() 返回当前线程对象

4.threading.enumerate() 返回当前存活即active的线程对象

5.threading.Event() 返回一个事件对象,可用set()将事件消息设置为true,也可用clear(),wait()设置等待,直到设置为true
<<详情参考>>

6.threading.local 是一个class类对象,拥有线程独有的data信息,不同的线程之间values值也不同
更详细的信息可用参考_threading_local模块

7.threading.Lock() 线程的锁对象,是一个基本的锁对象,一次只能一个锁定,其余锁请求,需等待锁释放后才能获取,
<<详情参考>>
7.threading.RLock() 多重锁,在同一线程中可用被多次acquire。如果使用RLock,那么acquire和release必须成对出现,
调用了n次acquire锁请求,则必须调用n次的release才能在线程中释放锁对象, <<详情参考>>

8.threading.Thread 一个线程控制器的对象

9.class threading.Timer 在间隔制定时间后执行线程, <<详情参考>>

10.threading.settrace(func) 在线程调用run()之前为所有的线程开启trace,实际调用的sys.settrace()

11.threading.setprofile(func) 在线程run()之前为线程设置profile属性值

12.threading.stack_size([size]) 堆栈size大小

13.threading.Semaphore([value]) 信号量,<<详情参考>>
13.threading.BoundedSemaphore([value]) 有界信号量,能够保证资源不超过vlaue值,默认1,<<详情参考>>

threading.Thread线程对象

定义:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
target调用对象,name线程名称,args=()参数

提供如下方法:

1.start()
2.run() 、 __init__() 可重写
3.join([timeout]) ,挂起进程,直到结束,也可设置超时时间,但超时后继续执行后续步骤,子进程不会退出,后面的示例会说明
4.getName()
5.setName() 也可以在线程对象创建时传入name参数
6.is_alive() / isAlive()
7.isDaemon()
8.setDaemon() 设置守护线程,<<详情参考>>

线程的一般使用:
start()
join()

示例:
基本的单个线程threading.Thread

#coding=utf8

import threading
import time

def showperson(name):
    print 'show person name :%s'%name

print '%s thread start!'%(time.ctime())
t =threading.Thread(target=showperson,args=("tom",))
t.start()
print '%s thread end!'%(time.ctime())

输出:

Sun May 28 16:37:01 2017 thread start!
show person name :tom
Sun May 28 16:37:01 2017 thread end!

改写为多个线程threading.Thread

#coding=utf8

import threading
import time

def showperson(name):
    print 'show person name :%s'%name

print '%s thread start!'%(time.ctime())

for i in range(3):
  t =threading.Thread(target=showperson,args=("person-%d"%i,))
  t.start()
print '%s thread end!'%(time.ctime
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值