线程简介:
threading 模块简介:
用于提供线程相关的操作,线程是应用程序中工作的最小单元。python当前版本的多线程库没有实现优先级、线程组,线程也不能被停止、暂停、恢复、中断。
threading 模块提供的类:
Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local。
threading 模块提供的常用方法:
threading.currentThread(): 得到线程对象。返回当前的线程变量。
threading.enumerate(): 返回一个包含正在运行的线程的list。正在运行指线程启动后、结束前,不包括启动前和终止后的线程。
threading.activeCount(): 返回正在运行的线程数量,与len(threading.enumerate())有相同的结果。
threading 模块提供的常量:
threading.TIMEOUT_MAX 设置threading全局超时时间。
创建线程的两种方法:
# -*- coding:utf-8 -*-
import threading
import time,random
def work(m,n,o):
print m, n, o # 结果:6 [1, 2] {'age': 25}
while True:
time.sleep(random.random())
print("播放上海滩")
# 创建线程和函数work关联
th = threading.Thread(target=work, name="liu", args=(6,[1,2],{"age":25}), kwargs={})
th.setDaemon(True)
th.start() # 启动线程
th.join() # 阻塞函数,等待回收线程
# 附加:如果没有th.join(),主线程退出后,
# -*- coding:utf-8 -*-
from threading import Thread
from time import ctime,sleep
# 编写自己的类,自定义线程类
class MyThread(Thread):
def __init__(self, func, args, name="dong"):
Thread.__init__(self)
# super().__init__()
self.func = func
self.args = args
self.name = name
# 线程调用start会自动运行
def run(self):
self.func(*self.args)
def player(file,sec):
for i in range(2):
print("playing %s:%s" % (file, ctime()))
sleep(sec)
thread1 = MyThread(player,("baby.mp3",3))
thread1.start()
thread1.join()
线程实例的方法:
构造方法:
Thread(group=None, target=None, name=None, args=(), kwargs={})
group: 线程组,目前还没有实现,库引用中提示必须是None;
target: 要执行的方法,线程函数。
name: 给线程取名字 (默认Thread-1)。
args/kwargs: 要传入方法的参数。args 元组:给线程函数位置传参。kwargs 字典:给线程函数字典传参。
实例方法:
isAlive(): 查看线程状态。返回线程是否在运行。正在运行指启动后、终止前。或者is_alive()方法。
getName(): 获取线程名称
setName("dong"): 设置线程名称。
setDaemon(bool): 设置是后台线程(默认前台线程(False))。(在start之前设置)
如果是后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,主线程和后台线程均停止。
如果是前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,主线程停止。
start(): 启动线程。线程准备就绪,等待CPU调度。
join([timeout]): 回收线程。阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout(可选参数)。
实例属性:
th.name:查看线程名称
th.daemon:默认为False,主线程执行完毕不会影响分支线程的执行,设置为True,则主线程执行完毕,其它线程也会终止。
th.isDaemon:判断daemon属性是True or False
# 设置daemon方法:th.daemon = True 或者 th.setDaemon(True)
# 附加1:没有th.join()时候,如果th.setDaemon(True),主进程结束,子进程也结束。如果th.setDaemon(False),主进程需要等待子进程结束,主进程才能结束。
# 附加2:有th.join()的时候,不管th.setDaemon(True)还是th.setDaemon(False),主进程都要等待子进程结束之后,主进程才能结束。
线程代码:
# -*- coding:utf-8 -*-
import threading
import time
def action(arg):
time.sleep(i)
print 'sub thread start!the thread name is:%s\r' % threading.currentThread().getName()
for i in range(4):
t =threading.Thread(target=action, args=(i,))
t.setDaemon(True) # 设置线程为后台线程
t.start()
print 'main_thread end!'
# 验证了serDeamon(False)前台线程,主线程执行过程中,前台线程也在进行,主线程执行完毕后,等待前台线程也执行完成后,主线程停止。
# 验证了serDeamon(True) 后台线程,主线程执行过程中,后台线程也在进行,主线程执行完毕后,后台线程不论成功与否,主线程均停止。
# -*- coding:utf-8 -*-
import threading,time
def fun(sec):
time.sleep(sec)
print("%s线程结束"%threading.currentThread().getName())
thread_list = []
for i in range(3):
t = threading.Thread(name="liu"+str(i), target=fun, args=(3,))
t.setDaemon(True)
thread_list.append(t)
for t in thread_list:
t.start()
for t in thread_list:
print t.name, t.is_alive()
t.join(6) # 不加参数6,会一直阻塞等待。
print("====主线程结束====")
# 验证了 join()阻塞当前上下文环境的线程,直到调用此方法的线程终止或到达指定的timeout,即使设置了setDeamon(True)主线程依然要等待子线程结束。
# 三个线程同时工作。线程回收的时候,等待第一个线程结束回收后,再回收第二个线程。
# 做几件事,就写几个函数。一个线程对应一个函数。
# wait(timeout)与join(timeout)带时间的。设置超时时间,如果不带时间参数,会一直阻塞等待。
https://www.cnblogs.com/tkqasn/p/5700281.html
https://blog.csdn.net/qwdafedv/article/details/84062717
https://blog.csdn.net/vgrant/article/details/86736921
https://blog.csdn.net/hzp666/article/details/78948998
https://blog.csdn.net/brucewong0516/article/details/81050792