day 32异步+回调、线程queue、线程Event、协程、单线程下实现遇到IO切换

一、异步+回调:线程是谁空谁调,进程是主进程调用

from concurrent.futures import ProcessPoolExcutor,ThreadPoolExecutor

from threading import current_thread

import requests,os,time,random

def get(url):

  print('%s GET %s'%(current_thread().name,url))

  response=requests.get(url)

  time.sleep(random.randint(1,3))

  if response.status_code=200:

    return response.text

def pasrse(obj):

  res=obj.result()

  print('%s 解析结果为:%s'%(current_thread().name,len(res)))

if __name__=='__main__':

  urls=[

'https://www.baidu.com',
'https://www.baidu.com',
'https://www.baidu.com',
'https://www.baidu.com',
'https://www.baidu.com',
'https://www.baidu.com',
'https://www.baidu.com',
'https://www.baidu.com',
'https://www.python.org',

]

  pool=ThreadPoolExecutor(4)

  for url in urls:

    obj=pool.submit(get,url)

    obj.add_done_callback(pasrse)

  print('主线程',current_thread().name)

二、queue

队列:先进先出

q.put(1)
q.put(2)
q.put(3)
# q.put(4)

print(q.get())
print(q.get())
print(q.get())

堆栈:后进先出
q.put('a')
q.put('b')
q.put('c')

print(q.get())
print(q.get())
print(q.get())

优先级队列:可以以小元组的形式往队列里存值,第一个元素代表优先级,数字越小优先级越高
q.put((10,'user1'))
q.put((-3,'user2'))
q.put((-2,'user3'))


print(q.get())
print(q.get())
print(q.get())

三、Event
from threading import Event,current_thread,Thread
import time

event=Event()

def check():
print('%s 正在检测服务是否正常....' %current_thread().name)
time.sleep(5)
event.set()


def connect():
count=1
while not event.is_set():
if count == 4:
print('尝试的次数过多,请稍后重试')
return
print('%s 尝试第%s次连接...' %(current_thread().name,count))
event.wait(1)
count+=1
print('%s 开始连接...' % current_thread().name)

if __name__ == '__main__':
t1=Thread(target=connect)
t2=Thread(target=connect)
t3=Thread(target=connect)

c1=Thread(target=check)

t1.start()
t2.start()
t3.start()
c1.start()

event.isSet():返回event的状态值;

event.wait():如果 event.isSet()==False将阻塞线程;

event.set(): 设置event的状态值为True,所有阻塞池的线程激活进入就绪状态, 等待操作系统调度;

event.clear():恢复event的状态值为False。

四、协程

1、单线程下实现并发:协程
并发指的多个任务看起来是同时运行的

并发实现的本质:切换+保存状态


并发、并行、串行:
并发:看起来是同时运行,切换+保存状态
并行:真正意义上的同时运行,只有在多cpu的情况下才能
实现并行,4个cpu能够并行4个任务

串行:一个人完完整整地执行完毕才运行下一个任务
from greenlet import greenlet
import time

def eat(name):
print('%s eat 1' %name)
time.sleep(30)
g2.switch('alex')
print('%s eat 2' %name)
g2.switch()
def play(name):
print('%s play 1' %name)
g1.switch()
print('%s play 2' %name)

g1=greenlet(eat)
g2=greenlet(play)

g1.switch('egon')
原文地址:https://www.cnblogs.com/lg04551/p/8967663.html