【目录】

一、 threading模块介绍

二 、开启线程的两种方式

三 、在一个进程下开启多个线程与在一个进程下开启多个子进程的区别

四、 线程相关的其他方法

五、守护线程 

六、Python GIL(Global Interpreter Lock)

八、同步锁

九、死锁现象与递归锁

十、线程queue

 

一、 threading模块介绍

进程的multiprocess模块,完全模仿了threading模块的接口,二者在使用层面,有很大的相似性,此处省略好多字。。

multiprocess模块用法回顾:https://www.cnblogs.com/bigorangecc/p/12759151.html

官网链接:https://docs.python.org/3/library/threading.html?highlight=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
    '''
谁的开启速度快

相关文章:

  • 2021-09-27
  • 2022-01-13
  • 2021-09-14
  • 2021-04-19
  • 2022-02-15
  • 2021-06-18
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-05-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案