Python1:threading模块的使用
本文参考《Tensorflow深度学习应用实践》一书。
(1)Thread类:
①功能:可用来创建线程;
②使用方法:创建一个threading.Thread对象,在初始化函数中将需要调用的对象作为初始化参数传入;
③应用举例:
import threading, time
# 函数功能:两线程对同一个数值进行操作
# 线程的共享变量
count = 0
class MyThread(threading.Thread):
def __init__(self, threadName):
super(MyThread, self).__init__(name=threadName)
# 重写run方法,在方法中将全局变量逐一增加
def run(self):
global count
for i in range(100):
count = count+1
time.sleep(0.3)
print(self.getName(), count)
for i in range(2):
MyThread("MyThreadingName:" + str(i)).start()
④运行结果:
由于每个线程自由地对共享变量进行访问,所以有时应该逐次打印的数值变成的两个相同的数值,如下图中的16和24.。
(2)Lock类:
①功能:
对当前运行中的线程进行锁定,只有当前线程被释放后,后续线程才可以继续操作;
②使用方法:
acquire方法提供了确定对象被锁定的标志,release在对象被当前线程使用完毕后将当前对象释放;
③应用举例:
import threading, time
import random
# 2.thread的锁定
# 函数功能:按顺序调用线程
count = 0
class MyThread(threading.Thread):
# Lock在构造函数中传递给MyThread
def __init__(self, lock, threadName):
super(MyThread, self).__init__(name=threadName)
self.lock = lock
# run方法中锁定当前线程,当前线程执行完毕后续线程才可以继续执行
def run(self):
global count
self.lock.acquire()
for i in range(5):
count = count+1
time.sleep(0.3)
print(self.getName(), count)
self.lock.release()
lock = threading.Lock()
for i in range(2):
MyThread(lock, "MyThreadingName:" + str(i)).start()
④运行结果:
线程1等待线程0完全结束后才执行后续的操作,逐次打印数值。
(3)Join类:
①功能:
用于堵塞当前主线程的类,作用是组织全部的线程继续运行,知道被调用的线程执行完毕或者超时。
②应用举例:
import threading, time
import random
# 3.thread的join类
# join类功能:用于堵塞当前主线程的类,阻止全部的线程继续运行
def doWaiting():
print('start waiting:', time.strftime('%S'))
time.sleep(3)
print('stop waiting', time.strftime('%S'))
thread1 = threading.Thread(target=doWaiting)
# 启动线程1
thread1.start()
time.sleep(1)
print('start join')
# 将一直堵塞,直到线程运行结束
thread1.join()
print('end join')