一. 引言:
python中关于多线程可通过thread和threading这两个模块来实现。thread相对来说,有一些缺陷,最明显的比如:当主线程退出的时候,所有其他线程还没有被清除就退出了;而threading会保证所有子线程退出后,进程才会结束。所以,这里只聚焦于threading模块。
二. 关于 threading:
threading 是 Python 处理多线程的标准库,支持创建线程、线程同步、线程通信等功能,使用简单且功能完善。
1. threading对象:
1). threading.activeCount() : 返回当前进程中线程的个数(包含主线程)。
2). threading.Condition() :条件变量能让一个线程停下来,等待其他线程满足某个"条件(状态或值)",主要用于线程同步。
3). threading.currentThread():获取当前的线程对象(Thread object)。
4). threading.enumerate():返回当前运行的Thread对象列表(包括后台线程,current_thread()创建的虚拟线程对象、主线程).
5). threading.Event() :通用的条件变量,多个线程等待某一个事件的发生,发生后,激活所有线程(一个线程向多个发送命令)。
6). class threading.local :线程内变量定义,如定义后会一直存在主线程中,并与生成的子线程共享。
7).threading.Lock(): 线程锁
8).threading.RLock(): 可重入锁对象,使单线程可以再次获得已经获得的锁(递归锁定).
9).threading.Semaphore([value]):为等待锁的线程提供缓冲区的大小。
10).threading.BoundedSemaphore([value]):与semaphore类似,但不允许超过初始值
11).class threading.Thread :一个线程执行的对象
12).class threading.Timer: 与Thread相似,但可等待一段时间允许(可用于定时器机制)
13).threading.settrace(func) :调用threading 模块(所有线程)的时候设定 跟踪函数(trace function )
14).threading.setprofile(func):设定 profile function
15).threading.stack_size([size]): 创建新线程时使用的线程的堆栈大小
16).exception threading.ThreadError: 异常 ....
2. Thread类:
threading的Thread是主要的允许对象,它有以下主要属性(函数):
threading.Thread(group=None, target=None, name=None.daemon=None, args=(), kwargs={})
参数:
group: 预留,用于扩展
target : 一个可调用对象(也称为活动[activity]),在线程启动后执行
name : 线程的名字。默认值为“Thread-N“,N是一个数字
args : 调用target时的参数列表和关键字参数
kwargs: 传递给 target 函数的关键字参数字典。
daemon:布尔值,指定线程是否为守护线程(后台线程)。
属性:
1).start() : 启动线程
2). run() :定义线程的功能函数(一般会被子类重写)
3). join([timeout]) :程序挂起,直到线程结束(如果给了timeout,最多阻塞timeout秒)
4). getName() : 获取线程对象名称
5). setName() : 设置线程对象名称
6). isAlive() : 检查线程是否在运行中
7). isDaemon() :返回线程的daemon标志(判断线程是否随主线程结束)
9). setDaemon() :设置后台进程
三. 案例:
创建线程要执行的函数,传进Thread对象中:
#!/usr/bin/python
import threading
import time
def thread_fun(num):
for i in range(0,int(num)):
print "from %s , num:%s" % (threading.currentThread().getName(),i)
time.sleep(1)
def main(thread_num):
thread_list = list()
for i in range(0,thread_num):
thread_name = "thread_%s" % i
thread_list.append(threading.Thread(target=thread_fun,args=(3,)))
for thread in thread_list:
thread.start()
for thread in thread_list:
thread.join()
main(3)
输出如下:
from Thread-1 , num:0
from Thread-2 , num:0
from Thread-3 , num:0
from Thread-1 , num:1
from Thread-2 , num:1
from Thread-3 , num:1
from Thread-1 , num:2
from Thread-2 , num:2
from Thread-3 , num:2
线程创建后需调用 start() 方法启动(而非直接调用 run(),run() 只是普通方法调用,不会创建新线程)。
args 和 kwargs 仅在 target 不为 None 时有效。
- - --------------------------------------------------------------------------------------------------------------------------
深耕运维行业多年,擅长运维体系建设,方案落地。欢迎交流!
“V-x”: ywjw996
《 运维经纬 》
3249

被折叠的 条评论
为什么被折叠?



