我正在试图弄清楚如何移植一个线程程序来使用asyncio.我有很多代码可以围绕几个标准库同步Queues,基本上是这样的:
import queue, random, threading, time
q = queue.Queue()
def produce():
while True:
time.sleep(0.5 + random.random()) # sleep for .5 - 1.5 seconds
q.put(random.random())
def consume():
while True:
value = q.get(block=True)
print("Consumed", value)
threading.Thread(target=produce).start()
threading.Thread(target=consume).start()
Run Code Online (Sandbox Code Playgroud)
一个线程创建值(可能是用户输入),另一个线程用它们做某事.关键是这些线程在有新数据之前一直处于空闲状态,此时它们会唤醒并对其执行某些操作.
我正在尝试使用asyncio实现这种模式,但我似乎无法弄清楚如何让它"去".
我的尝试看起来或多或少都像这样(并且根本不做任何事情).
import asyncio, random
q = asyncio.Queue()
@asyncio.coroutine
def produce():
while True:
q.put(random.random())
yield from asyncio.sleep(0.5 + random.random())
@asyncio.coroutine
def consume():
while True:
value = yield from q.get()
print("Consumed", value)
# do something here to start the coroutines. asyncio.Task()? …Run Code Online (Sandbox Code Playgroud) Scipy最小化函数(仅用作示例),可以选择在每一步添加回调函数.所以我可以做点什么,
def my_callback(x):
print x
scipy.optimize.fmin(func, x0, callback=my_callback)
Run Code Online (Sandbox Code Playgroud)
有没有办法使用回调函数来创建fmin的生成器版本,这样我才能做到,
for x in my_fmin(func,x0):
print x
Run Code Online (Sandbox Code Playgroud)
似乎可能有一些产量和发送的组合,但我可以想到任何事情.