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,Threadimport 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 greenletimport 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

时间: 2024-07-31 04:54:31

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

python—day32 异步 + 回调 、Event、gevent 、协程、单线程下实现遇到IO切换

异步 + 回调:就是把下载好的东西回调主进程执行 或者回调给线程,哪个线程闲着就执行 1 #进程的异步 + 回调 2 # from concurrent.futures import ProcessPoolExecutor,ThreadPoolExecutor 3 # 4 # import requests 5 # import os,time,random 6 # def get(url): 7 # print('%s get %s'%(os.getpid(),url) ) 8 # 9 # r

Python:线程、进程与协程(3)——Queue模块及源码分析

Queue模块是提供队列操作的模块,队列是线程间最常用的交换数据的形式.该模块提供了三种队列: Queue.Queue(maxsize):先进先出,maxsize是队列的大小,其值为非正数时为无线循环队列 Queue.LifoQueue(maxsize):后进先出,相当于栈 Queue.PriorityQueue(maxsize):优先级队列. 其中LifoQueue,PriorityQueue是Queue的子类.三者拥有以下共同的方法: qsize():返回近似的队列大小.为什么要加"近似&q

python线程、进程和协程

链接:http://www.jb51.net/article/88825.htm 引言 解释器环境:python3.5.1 我们都知道python网络编程的两大必学模块socket和socketserver,其中的socketserver是一个支持IO多路复用和多线程.多进程的模块.一般我们在socketserver服务端代码中都会写这么一句: server = socketserver.ThreadingTCPServer(settings.IP_PORT, MyServer) Threadi

线程、进程与协程2

一.协程 什么是协程? 协程,又名微线程,纤程,英文名为Coroutine. 协程是一种用户态的轻量级线程. 协程拥有自己的寄存器上下文和栈.协程调度切换时,将寄存器上下文和栈保存到其他地方,在切回来的时候,恢复先前保存的寄存器上下文和栈. 因此,协程能保留上一次调用时的状态(即所有局部状态的一个特定组合),每次过程重入时,就相当于进入上一次调用的状态,换种说法:进入上一次离开时所处逻辑流的位置. CPU只认识线程,不认识协程.线程的寄存器在CPU上,协程的寄存器不在CPU上. yield就是在

Python:线程、进程与协程(4)——multiprocessing模块(1)

multiprocessing模块是Python提供的用于多进程开发的包,multiprocessing包提供本地和远程两种并发,通过使用子进程而非线程有效地回避了全局解释器锁. (一)创建进程Process 类 创建进程的类,其源码在multiprocessing包的process.py里,有兴趣的可以对照着源码边理解边学习.它的用法同threading.Thread差不多,从它的类定义上就可以看的出来,如下: class Process(object):     '''     Proces

Python:线程、进程与协程(2)——threading模块(1)

上一篇博文介绍了Python中线程.进程与协程的基本概念,通过这几天的学习总结,下面来讲讲Python的threading模块.首先来看看threading模块有哪些方法和类吧. 主要有: Thread :线程类,这是用的最多的一个类,可以指定线程函数执行或者继承自它都可以实现子线程功能. Timer:与Thread类似,但要等待一段时间后才开始运行,是Thread的子类. Lock :原锁,是一个同步原语,当它锁住时不归某个特定的线程所有,这个可以对全局变量互斥时使用. RLock :可重入锁

Python之路【第七篇】:线程、进程和协程

Python之路[第七篇]:线程.进程和协程 Python线程 Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 #!/usr/bin/env python # -*- coding:utf-8 -*- import threading import time   def show(arg):     time.sleep(1)     print 'thread'+str(arg)   for i in

线程、进程、协程和GIL(一)

参考链接:https://www.cnblogs.com/alex3714/articles/5230609.html https://www.cnblogs.com/work115/p/5620272.html 编程离不开并发,而并发的基础就离不开线程.进程.协程.那么什么是线程.进程.协程呢? 进程: 进程是对资源进行分配和调度的最小单位,是操作系统结构的基础,是线程的容器(就像是一幢房子,一个空壳子,并不能运动). 线程的概念主要有两点: 1.进程是一个实体,每个进程都有自己的地址空间,一

Python菜鸟之路:Python基础-线程、进程、协程

上节内容,简单的介绍了线程和进程,并且介绍了Python中的GIL机制.本节详细介绍线程.进程以及协程的概念及实现. 线程 基本使用 方法1: 创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入 import threading import time def worker(): time.sleep(2) print("test") for i in range(5): t = threading.Thread(target=