threading模块
线程运行在进程内部,可以访问进程的所有内容。
线程内尽量不要共享全局变量,在需要修改共同数据的情况下,使用线程锁
threading模块的常用方法:
thread = threading.Thread(target=None, name=None, daemon=None, group=None, args=(), kwargs={})
# 实例化一个线程
# target是线程调用run()方法的时候会调用的函数
# 参数args和kwargs分别表示调用target时的参数列表和关键字参数
# name是该线程名称
# daemon=True时,thread dies when main thread (only non-daemon thread) exits.
thread.start() # 一个线程最多只能调用该方法一次,如果多次调用则会报RuntimeError错误。它会调用run方法
thread.run() # 在这里运行线程的具体任务
thread.join(timeout=None) # 阻塞全部线程直到当前线程任务结束,timeout为阻塞时间,None时会一直阻塞
thread.name
thread.getName()
thread.setName()
thread.is_alive() # 判断当前进程是否存活
threading.active_count() # 返回当前线程对象Thread的个数
threading.current_thread() # 返回当前的线程对象Thread
threading.current_thread().name # 返回当前线程的名称
简单实例:
import datetime
import threading
class ThreadClass(threading.Thread):
def run(self):
now = datetime.datetime.now()
print("%s says Hello World at time: %s" % (self.getName(), now))
for i in range(2):
t = ThreadClass()
t.start()
# Thread-1 says Hello World at time: 2008-05-13 13:22:50.252069
# Thread-2 says Hello World at time: 2008-05-13 13:22:50.252576
# 启动一个线程
thread.start()
# 继承threading.Thread
import threading
class ThreadClass(threading.Thread):
# 初始化方法
def __init__(self, threadName):
threading.Thread.__init__(self)
self.threadName = threadName
# 运行线程时会被调用的run方法
def run(self):
print('{0} is start'.format(self.threadName))
# 关闭一个进程
thread.join()
# join方法会暂时阻塞进程,等待子进程结束后再继续往下运行