python coroutine_python coroutine

python coroutine

前言

OOAD课程是用python教的,其中涉及到大量的python语法糖,老师也算是手把手教如何写出OO的python,但一个学期没听课只能期末补一补。

Coroutines

Coroutines are similar to generators with a few differences. The main differences are:

generators are data producers generators制造数据

coroutines are data consumers coroutines消费数据

来看第一个代码示例,通过send()接收数据,然后进行比对,找出含有关键字的数据并打印。

def grep(pattern):

print("Searching for", pattern)

while True:

line = (yield)

if pattern in line:

print(line)

search = grep('coroutine')

next(search)

# Output: Searching for coroutine

search.send("I love you")

search.send("Don't you love me?")

search.send("I love coroutines instead!")

很明显我们可以看到,yield关键字在这里已经从返回数据的变为接收数据的。也就是,Python的yield不但可以返回一个值,它还可以接收调用者发出的参数。

在中文里,coroutine对应的是协程,但是显然老师的重点不是什么同步异步,而是yield,以及coroutine和subprogram的区别。

Subprogram vs Coroutine, is (programming) a piece of code that performs a task, and that can be passed new input and return output more than once. As nouns the difference between subroutine and coroutine is that subroutine is (computer science) a section of code, called by the main body of a program, that implements a task while coroutine is (programming) a piece of code that performs a task, and that can be passed new input and return output more than once.

放上老师PPT的测试代码就收工:

def coroutine(y):

for i in range(y):

x = yield i

print("i=%d , x=%d " % (i, x))

c = coroutine(4)

next(c)

c.send(10)

c.send(20)

c.send(30)

25a9b86a3ad93f12f9de1eeaeba3b37b.png

def echo():

just_received='nothing'

try:

while True:

received=yield just_received

just_received=received

print('I got {}.'.format(just_received))

except GeneratorExit:

# when closed with close()

print('Coroutine closed!')

g = echo()

next(g)

g.send('test1')

g.send('test2')

g.close()

cbb77b049b866b6deae1267da5fefc73.png

Reference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个关于使用 `asyncio.run_coroutine_threadsafe()` 进行消息队列入队出队的示例: ```python import asyncio import queue # 创建一个消息队列 message_queue = queue.Queue() # 定义一个协程,用于从队列中获取消息 async def consume_message(): while True: # 从队列中获取消息 message = message_queue.get() # 处理消息 print("Consumed message:", message) # 定义一个函数,用于将消息发送到队列中 def send_message(message): # 将消息推入队列 message_queue.put(message) # 在事件循环中异步调用 consume_message() 协程 asyncio.run_coroutine_threadsafe(consume_message(), loop) # 创建一个事件循环 loop = asyncio.get_event_loop() # 启动消费者协程 asyncio.ensure_future(consume_message()) # 发送一些消息 send_message("Hello, world!") send_message("How are you?") send_message("Goodbye!") # 运行事件循环 loop.run_forever() ``` 在上面的示例中,我们首先创建了一个简单的消息队列 `message_queue`。然后,我们定义了一个协程 `consume_message()`,它会从队列中获取消息并进行处理。 接下来,我们定义了一个函数 `send_message()`,用于将消息发送到队列中。在这个函数中,我们首先将消息推入队列中,然后使用 `asyncio.run_coroutine_threadsafe()` 方法在事件循环中异步调用 `consume_message()` 协程。 最后,我们创建一个事件循环,并使用 `asyncio.ensure_future()` 启动消费者协程。然后,我们调用 `send_message()` 函数发送一些消息,并运行事件循环。在事件循环中,我们将一直等待新的消息,并使用 `consume_message()` 协程进行处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值