【目录】
一、 threading模块介绍
二 、开启线程的两种方式
三 、在一个进程下开启多个线程与在一个进程下开启多个子进程的区别
四、 线程相关的其他方法
五、守护线程
六、Python GIL(Global Interpreter Lock)
八、同步锁
九、死锁现象与递归锁
十、线程queue
一、 threading模块介绍
进程的multiprocess模块,完全模仿了threading模块的接口,二者在使用层面,有很大的相似性,此处省略好多字。。
二 、开启线程的两种方式
1、实例化类创建对象
#方式一
from threading import Thread
import time
def sayhi(name):
time.sleep(2)
print('%s say hello' %name)
if __name__ == '__main__':
t=Thread(target=sayhi,args=('egon',))
t.start()
print('主线程')
2、类的继承
#方式二
from threading import Thread
import time
class Sayhi(Thread):
def __init__(self,name):
super().__init__()
self.name=name
def run(self):
time.sleep(2)
print('%s say hello' % self.name)
if __name__ == '__main__':
t = Sayhi('egon')
t.start()
print('主线程')
三 、在一个进程下开启多个线程与在一个进程下开启多个子进程的区别
1、比较开启速度
![]()
from threading import Thread
from multiprocessing import Process
import os
def work():
print('hello')
if __name__ == '__main__':
#在主进程下开启线程
t=Thread(target=work)
t.start()
print('主线程/主进程')
'''
打印结果:
hello
主线程/主进程
'''
#在主进程下开启子进程
t=Process(target=work)
t.start()
print('主线程/主进程')
'''
打印结果:
主线程/主进程
hello
'''
谁的开启速度快