标签:函数名 inspect 产生 并发 python 过程 multi 指定 资源
def xc():
print("协程开始")
#yield既是出口,也是入口
a = yield
print("协程从新开始:", a)
#实例一个协程
x = xc()
print("11111")
#此步骤可以使用next(x)
#开始执行,也叫预激
x.send(None)
print("22222")
x.send("haha")
def A():
for i in [1, 2]:
yield i
print(list(A()))
def B():
#相当于在list和[1, 2]间的中间地带
yield from [1, 2]
print(list(B()))
import threading
import asyncio
@asyncio.coroutine
def hello():
print('Hello world! (%s)' % threading.currentThread())
#跳出协程,睡5秒
yield from asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
#启动消息循环
loop = asyncio.get_event_loop()
#定义要执行的任务
tasks = [hello(), hello()]
#asyncio使用wati等待task执行完毕
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
#执行结果
Hello world! (<_MainThread(MainThread, started 2400)>)
Hello world! (<_MainThread(MainThread, started 2400)>)
Hello again! (<_MainThread(MainThread, started 2400)>)
Hello again! (<_MainThread(MainThread, started 2400)>)
import time
from concurrent import futures
def return_futures(a):
time.sleep(2)
return a
#创建一个线程池,max_workers工作线程数量
s = futures.ThreadPoolExecutor(max_workers=2)
#向线程池中加入两个任务
r1 = s.submit(return_futures, "hi")
r2 = s.submit(return_futures, "hello")
#判断两个线程执行状态
print(r1.done())
print(r2.done())
time.sleep(3)
print(r1.done())
print(r2.done())
#输出两个线程的结果
print(r1.result())
print(r2.result())
import time
from concurrent import futures
def wait_on(a):
print(a)
time.sleep(2)
return "ok"
l = [1, 2]
t = futures.ThreadPoolExecutor(max_workers=2)
for i in t.map(wait_on, l):
print(i)
标签:函数名 inspect 产生 并发 python 过程 multi 指定 资源
原文地址:https://www.cnblogs.com/TK-tank/p/12316220.html