上QQ阅读APP看书,第一时间看更新
ThreadPoolExecutor in practice
In this example, we analyze the creation of an object of the ThreadPoolExecutor class. We define a view_thread() function that allows us to display the current thread identifier with the threading.get_ident() method.
We define our main function where the executor object is initialized as an instance of the ThreadPoolExecutor class and over this object we execute a new set of threads. Then we obtain the thread has been executed with the threading.current_thread() method.
You can find the following code in the threadPoolConcurrency.py file in concurrency subfolder:
#python 3
from concurrent.futures import ThreadPoolExecutor
import threading
import random
def view_thread():
print("Executing Thread")
print("Accesing thread : {}".format(threading.get_ident()))
print("Thread Executed {}".format(threading.current_thread()))
def main():
executor = ThreadPoolExecutor(max_workers=3)
thread1 = executor.submit(view_thread)
thread1 = executor.submit(view_thread)
thread3 = executor.submit(view_thread)
if __name__ == '__main__':
main()
We see that the three different values in the script output are three different thread identifiers, and we obtain three distinct daemon threads: