Created
February 20, 2018 05:21
-
-
Save kittinan/ed00fca4ad2459b4339ae32a82cd7d8b to your computer and use it in GitHub Desktop.
Python 3 Thread Pool Sample
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
| # Ref: http://masnun.com/2016/03/29/python-a-quick-introduction-to-the-concurrent-futures-module.html | |
| import time | |
| import random | |
| from concurrent.futures import ThreadPoolExecutor, wait, as_completed | |
| def add(name): | |
| res = random.randint(1, 5) | |
| res = 2 | |
| time.sleep(res) | |
| print("[!] {}: {}".format(name, res)) | |
| return name | |
| pool = ThreadPoolExecutor(5) | |
| futures = [] | |
| for x in range(10): | |
| futures.append(pool.submit(add, "Thread-{}".format(x))) | |
| print("Added: Thread-{}".format(x)) | |
| for x in as_completed(futures): | |
| print("{} completed".format(x.result())) | |
| print("Done") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment