文章目录
一. 并发编程
1. 概述
- 非并发
(1)程序由单个步骤序列构成
(2)包括独立子任务的程序执行性能低 - 并发
(1)异步、高效
(2)分解子任务、简化流程与逻辑 - 进程 process
(1)一个程序的执行实例
(2)每个进程都有自己的独立的地址空间、内存、数据线及辅助数据 - 线程 thread
(1)统一进程内,可被并行激活的控制流
(2)共享相同上下文(空间地址、数据结构)
(3)特点:便于信息共享和通讯,线程访问顺序差异会导致结果不一致(条件 race condition) - Python GIL 全局解释器锁
(1) Global Interpreter Lock
(2) Python 代码由虚拟机(解释器主循环)控制
(3)主循环同时只能有一个控制线程执行
2. 多线程
- _thread(不建议使用)
(1)特点:没有控制进程结束的机制,只有一个同步原语(锁),功能少于threading模块
import time
import _thread
def worker(n):
print(f'time start: {time.ctime()}')
time.sleep(n)
print(f'time end: {time.ctime()}') #获取当前线程
def main():
print(f'[start: {time.ctime()}]')
_thread.start_new_thread(worker,(4,)) #开始线程
_thread.start_new_thread(worker,(2,))
time.sleep(4)
print(f'[end: {time.ctime()}]')
if __name__ == '__main__':
main()
- threading模块
(1) .Thread 线程类
import time
import threading
def worker(n):
print(f'{threading.current_thread().name}time start: {time.ctime()}')
time.sleep(n)
print(f'{threading.current_thread().name}time end: {time.ctime()}')
def main():
print(f'[start: {time.ctime()}]')
threads = []
t1 = threading.Thread(target=worker,args=(4,))
threads.append(t1)
t2 = threading.Thread(target=worker, args=(2,))
threads.append(t2)
for t in threads:
t.start()
for t in threads:
t.join() #告诉主线程等待当前线程执行完毕
print(f'[end: {time.ctime()}]')
if __name__ == '__main__':
main()
自定义一个派生类
import time
import threading
def worker(n):
print(f'{threading.current_thread().name}time start: {time.ctime()}')
time.sleep(n)
print(f'{threading.current_thread().name}time end: {time.ctime()}')
class MyThread(threading.Thread):
def __init__(self,func,args):
threading.Thread.__init__(self)
self.func = func
self.args = args
def run(self):
self.func(*self.args)
def main():
print(f'[start: {time.ctime()}]')
threads = []
t1 = MyThread(worker,args=(4,))
threads.append(t1)
t2 = MyThread(worker, args=(2,))
threads.append(t2