如何使用多线程
创建一个线程类来封装数据
from threading import Thread
from time import sleep
def handle(sid):
print('Download...(%d)' % sid)
sleep(2)
print('Convert to...(%d)' % sid)
class MyThread(Thread): # 自定义线程类
def __init__(self, sid):
# Thread.__init__(self)
super(MyThread, self).__init__() # 必须调用 父类的构造器 这是py2的语法,py3是super().__init__()
self.sid = sid # 使用类,能够更好的封装数据
def run(self): # 新建程序的入口点,和target类似
handle(self.sid) # 更常见的做法是将handle也做为这个类的方法
if __name__ == '__main__':
t = MyThread(1)
t.start()
t.join()
print('main thread')
如何实现线程间的通信
GIL
在每个进程中, 存在一把GIL, 该进程中的线程间共享GIL
多线程进行时, 只有有GIL的那个线程能运行
通过线程间快速 传递GIL, 达到表象上的多线程, 其实同一时间只有一个线程在工作
解决方案: