13.1 threading 模块
BC3BA70FAEE8FE851CA38B0C49F897CA.jpg
简单演示该模块方法:
>>> import threading
>>> threading.stack_size() # 查看当前线程栈大小
0
>>> threading.stack_size(64 * 1024) # 设置当前线程栈大小
0
>>> threading.active_count() # 当前活动线程数量
2
>>> threading.current_thread() # 当前线程对象
<_MainThread(MainThread, started 13100)>
>>> threading.enumerate() # 当前活动线程对象列表
[<_MainThread(MainThread, started 13100)>, <Thread(SockThread, started daemon 10460)>]
13.2.1 Thread 对象中的方法
Thread 类创建线程对象,调用其 start() 方法来启动,该方法自动调用该类对象的 run() 方法,此时该线程处于 alive 状态,直到 run() 方法运行结束。
2C59040A0A67981D2B7D841B6CD394E5.jpg
(1)join([timeout)) :阻塞当前线程,等待被调线程结束或超时后再执行当前线程的后续代码。
import threading
import time
def func(x, y):
for i in range(x, y):
print(i, end = ' ')
time.sleep(10)
t1 = threading.Thread(target = func, args = (15, 20))
t1.start()
t1.join(5)
t2 = threading.Thread(target = func, args = (5, 10))
t2.start()
(2)is_alive() :测试线程是否处于运行状态。
import threading
import time
def func(x, y):
for i in range(x, y):
print(i, end = ' ')
# time.sleep(10)
t1 = threading.Thread(target = func, args = (15, 20))
t1.start()
t1.join(5)
t2 = threading.Thread(target = func, args = (5, 10))
t2.start()
print('t1:', t1.is_alive())
print('t2:', t2.is_alive())
13.2.2 Thread 对象中的 daemon 属性
当某子线程的 daemon 属性为 True 时,主线程运行结束时不对该子线程进行检查直接退出,同时所有 daemon 值为 True 的子线程将随主线程一切结束,不论是否完成。daemon 属性默认为 False,如需修改,必须在 start() 方法之前修改。
import threading
import time
class mythread(threading.Thread):
def __init__(self, num, threadname):
threading.Thread.__init__(self, name = threadname)
self.num = num
def run(self):
time.sleep(self.num)
print(self.num)
t1 = mythread(1, 't1')
t2 = mythread(5, 't2')
t2.daemon = True
print(t1.daemon)
print(t2.daemon)
t1.start()
t2.start()
派生自 Thread 类的自定义线程类首先也是一个普通类,同时拥有线程类的 run()、start()、join()等方法。
import threading
import time
class myThread(threading.Thread):
def __init__(self, threadName):
threading.Thread.__init__(self)
self.name = threadName
def run(self):
time.sleep(1)
print('In run:', self.name)
def output(self): # 在线程类中定义普通方法
print('In output:', self.name)
t = myThread('test')
t.start()
t.output() # 调用普通方法
time.sleep(2)
print('OK')