Python
Coroutine
Basic usage of coroutines.
By EZ4Code Team
coroutinecoroutine
Code
import asyncio
async def producer(queue):
for i in range(5):
await asyncio.sleep(0.1)
await queue.put(i)
await queue.put(None) # End signal
async def consumer(queue):
while True:
item = await queue.get()
if item is None:
break
print(f"Consumed: {item}")
queue.task_done()
async def main():
q = asyncio.Queue()
await asyncio.gather(producer(q), consumer(q))
asyncio.run(main())Explanation
Coroutines implement cooperative concurrency via async/await, suitable for IO-intensive tasks.
More Python Snippets
Sort Dictionary by Value
Sort a Python dictionary by its values in descending order.
List Comprehension
Quickly generate lists using list comprehensions.
Dictionary Merging
Multiple ways to merge dictionaries.
File Read/Write
Various ways to read and write files.
CSV Processing
Read and write CSV files using the csv module.
JSON Processing
JSON serialization and deserialization.