Skip to content

Instantly share code, notes, and snippets.

@tiandiao123
Last active November 16, 2022 22:47
Show Gist options
  • Save tiandiao123/0e314c5f1f5d7af9404c9f32418060ff to your computer and use it in GitHub Desktop.
Save tiandiao123/0e314c5f1f5d7af9404c9f32418060ff to your computer and use it in GitHub Desktop.
# the following codes are modified from https://www.bilibili.com/video/BV155411V7tj/?spm_id_from=333.337.search-card.all.click&vd_source=0e3bf657889554538e4fce27455e8e66
import os
import asyncio
import time
class GatherApples:
def __init__(self):
self.apples = [1]
async def ask_for_apple(self):
await asyncio.sleep(1)
self.apples.append(1)
async def take_apples(self, num):
count = 0
while True:
if len(self.apples) == 0:
await self.ask_for_apple()
else:
cur_apple = self.apples.pop()
yield cur_apple
count += 1
if count == num:
break
async def buy_apples(self):
bucket = []
async for p in self.take_apples(10):
bucket.append(p)
print(bucket)
def run_loop(self):
loop = asyncio.get_event_loop()
res = loop.run_until_complete(self.buy_apples())
loop.close()
if __name__ == "__main__":
my_runner = GatherApples()
my_runner.run_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment