2021/6/13 并发编程-线程

'''
线程理论
from multiprocessing.Manager import Queue
进程:资源单位,创建进程就是向系统申请各种资源
线程;执行单位,线程就是用于执行任务的,执行任务过程中所需的资源均向进程索要
每一个进程内必定会有一个主线程
内核线程:由操作系统内核创建、撤销
用户线程:由用户在进程内手动创建、撤销
线程模块:
_thread(为兼容thread)
threading(python3)

开启线程的两种方式
1. from threading import Thread
t = Thread(func, args=(), kwargs={}, name, group=None)
t.start()
2. from threading import Thread
class xxx(Thread):
def run():
xxx
x = xxx()
x.start()
threading
Thread(func, args=(), kwargs={}, name, group=None)
.start()
.join([timeout])
.is_alive()/isAlive()
.terminate()
.name/getName()/setName()
.daemon/isDaemon/setDaemon()
current_thread()/currentThread()
enumerate()
active_count()/activeCount()
Lock()
.acquire()
.replace()
RLock()
.acquire()
.acquire()
.replace()
.replace()
Semaphore
.acquire()
.replace()
Event
.isSet()/is_set()
.wait()
.set()
.clear()

GIL全局解释器锁
GIL不是python的特点而是CPython的特点
GIL是用于保护解释器的数据安全,同一时刻只能有一个线程获取解释器执行权限
GIL导致单进程下多线程无法利用多核优势
所有解释性语言的通病:单进程下多线程无法利用多核优势
计算密集型:多进程
IO密集型:多线程
死锁现象:
线程A获取到锁B需要获取锁A,线程B获取到锁A需要获取锁B
queue
from queue import Queue, LifoQueue, PriorityQueue
先入先出队列
后入先出队列
优先级队列
.put((优先级,obj))
Future
from concurrent.futures import ThreadPoolExecutor
submit(func, *args, **kwargs)
.cancel()
.cancelled()
.running()
.done()
.result([timeout])
.exception([timeout])
.add_done_callback(fn)
terminate()
map(func, iterable, timeout=None, chunksize=1)

协程:
单进程下实现高并发
1. 监测IO gevent
from gevent import spawn
from gevent import monkey;monkey.patch_all()
spawn(func, *args)
join()
2. 切换 greenlet
import greenlet
.greenlet(func)
.switch(参数)
3. 状态记录 yield
IO模型
阻塞IO
非阻塞IO
多路复用IO
异步IO
信号驱动IO

'''
posted @ 2021-06-13 12:27  zzwYYYYYY  阅读(59)  评论(0)    收藏  举报