线程是操作系统内核调度的基本单位,一个进程中包含一个或多个线程,同一个进程内的多个线程资源共享,线程相比进程是“轻”量级的任务,内核进行调度时效率更高。
多线程可以实现多任务并发执行,简化代码的编写难度,每一个独立的模块都可以设计成一个独立的线程运行
线程间通信比进程间通信难度更小,效率更高,因为资源共享
线程的调度比进程的调度效率高
Python 语言内置了多线程功能支持,而不是单纯地作为底层操作系统的调度方式,从而简化了 Python 的多线程编程
import threading import time def runOne(info): while True: print(info) time.sleep(1) pass def runTwo(info): while True: print(info) time.sleep(1) pass if __name__ == ‘__main__‘: t1 = threading.Thread(target = runOne, args = ("task one run",)) t2 = threading.Thread(target = runTwo, args = ("task two run",)) t1.start() # 启动t1 t2.start() # 启动t2 t1.join() # 主线程等待t1子线程结束(阻塞) t2.join() # 主线程等待t2子线程结束(阻塞)
import threading import time class MyThread(threading.Thread): def __init__(self, info): super(MyThread, self).__init__() self.info = info def run(self): while True: print(self.info) time.sleep(1) pass if __name__ == "__main__": t1 = MyThread("taskone") t2 = MyThread("tasktwo") t1.start() # 启动t1 t2.start() # 启动t2 t1.join() # 主线程等待t1子线程结束(阻塞) t2.join() # 主线程等待t2子线程结束(阻塞)
如果将任务1设置为任务2的守护线程,当任务1结束时,任务2也自动结束。上述例子中如果将子线程设置主线程的守护线程,那么当子线程结束时,守护线程也自动结束。
import threading import time class MyThread(threading.Thread): def __init__(self, info): super(MyThread, self).__init__() self.info = info def run(self): print(self.info) time.sleep(1) print(self.info) time.sleep(1) pass if __name__ == "__main__": t1 = MyThread("taskone") t1.setDaemon(True) # t1设置为主线程的守护线程 t1.start() # 启动t1
为了实现子线程结束后,主线程再结束的目的,可以使用join方法,让主线程等待子线程执行。
import threading import time class MyThread(threading.Thread): def __init__(self, info): super(MyThread, self).__init__() self.info = info def run(self): print(self.info) time.sleep(1) print(self.info) time.sleep(1) print("Sub tash end") pass if __name__ == "__main__": t1 = MyThread("taskone") t1.start() # 启动t1 t1.join() # 主线程等待子线程结束 print("main task end")
原文:https://www.cnblogs.com/chusiyong/p/12898739.html