Skip to content

Instantly share code, notes, and snippets.

@mjrulesamrat
Last active Jun 25, 2019
Embed
What would you like to do?
Concurrency in python snippets
################ threading.py
import threading
def my_task():
print("Hello world: {}".format(threading.current_thread()))
# my_task()
my_thread = threading.Thread(target=my_task)
my_thread.start()
################# thread_pool.py
import threading
from concurrent.futures import ThreadPoolExecutor
def task():
print("Executing a task")
result = 0
for i in range(10):
result += i
print("Result: {}".format(result))
print("Task was executed by: {}".format(threading.current_thread()))
def main():
# three threads
executor = ThreadPoolExecutor(max_workers=3)
task1 = executor.submit(task)
task2 = executor.submit(task)
task3 = executor.submit(task)
if __name__ == "__main__":
main()
################# python_asyncio.py
import asyncio
async def my_coroutine():
print("My simple coroutine")
@asyncio.coroutine
def my_coroutine_2():
print("My coroutine 2")
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(my_coroutine())
loop.run_until_complete(my_coroutine_2())
loop.close()
main()
################# python_asyncio_1.py
import asyncio
import random
async def my_coroutine(id):
process_time = random.randint(3, 5)
await asyncio.sleep(process_time)
print("Courotine {}, has successfully completed after {} seconds".format(id, process_time))
async def main():
tasks = []
for i in range(10):
tasks.append(asyncio.ensure_future(my_coroutine(i)))
await asyncio.gather(*tasks)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment