官网链接: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 '''