Last active
June 25, 2019 13:58
-
-
Save mjrulesamrat/961110a12cc5e508a2aa5cba836364a0 to your computer and use it in GitHub Desktop.
Concurrency in python snippets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################ 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