官网链接:https://docs.python.org/3/library/threading.html?highlight=threading#

1.开启线程的两种方式

#直接调用
import threading
import time
def run(n):
    print('task',n)
     time.sleep(2)

t1 = threading.Thread(target=run,args=('t1',))
t1.start()
#继承式调用
mport threading
import time
class MyThread(threading.Thread):
    def __init__(self,n,sleep_time):
        super(MyThread, self).__init__()
        self.n = n
        self.sleep_time = sleep_time

    def run(self):
        print('running task',self.n)
        time.sleep(self.sleep_time)
        print('task done,',self.n)

t1 = MyThread('t1',2)
t1.start()

2.在一个进程下开启多个线程与在一个进程下开启多个子进程的区别

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
    '''
1.开启速度比较

相关文章:

  • 2021-06-21
  • 2022-01-03
猜你喜欢
  • 2021-12-14
  • 2022-01-13
  • 2018-09-12
  • 2022-02-09
  • 2022-01-20
  • 2022-02-21
  • 2021-12-04
相关资源
相似解决方案