#线程开启一 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('主线程')
#开启线程方式二 from threading import Thread import time class Sayhi(Thread): def __init__(self,name): super().__init__() self.name = name def run(self): #名字必须为run time.sleep(2) print('%s say hello'%self.name) if __name__ == '__main__': t = Sayhi('egon') t.start() #start开始会运行run函数 print('主线程')
在一个进程字儿开启多个线程与开启多个进程的区别
from threading import Thread #线程模块 from multiprocessing import Process #进程模块 import os def work(): print('hello') if __name__ == '__main__': # t = Thread(target=work) #开启线程速度较快 t = Process(target=work) #重新申请内存空间,速度慢 t.start() print('主线程:%s'%os.getpid())
线程与进程的区别
线程中所有的数据共享
守护线程与守护进程的异同:
主线程会等到所有非守护线程结束,才销毁守护线程
主进程的代码运行完毕,就会销毁守护进程,然后等非守护进程运行完毕,主进程结束。
1 from threading import Thread 2 import time 3 def foo(): 4 print(123) 5 time.sleep(2) 6 print('end123') 7 def bar(): 8 print(456) 9 time.sleep(1) 10 print('end456') 11 if __name__ == '__main__': 12 t1 = Thread(target=foo) 13 t2 = Thread(target=bar) 14 t1.daemon = True 15 t1.start() 16 t2.start() 17 print('this is father')