进程池

from concurrent.futures import ProcessPoolExecutor
import os

def task():
print("Executing our Task on Process {}".format(os.getpid()))

def main():
executor = ProcessPoolExecutor(max_workers=3)
task1 = executor.submit(task)
task2 = executor.submit(task)

if __name__ == '__main__':
main()

上下文进程池

from concurrent.futures import ProcessPoolExecutor
import os

def task():
print("Executing our Task on Process: {}".format(os.getpid()))

def main():
# executor = ProcessPoolExecutor(max_workers=3)
with ProcessPoolExecutor(max_workers=3) as executor:
task1 = executor.submit(task)
task2 = executor.submit(task)

main()

线程池

from concurrent.futures import ThreadPoolExecutor
import threading
import random

def task():
print("Executing our Task")
result = 0
i = 0
for i in range(10):
result = result + i
print("I: {}".format(result))
print("Task Executed {}".format(threading.current_thread()))

def main():
executor = ThreadPoolExecutor(max_workers=3)
task1 = executor.submit(task)
task2 = executor.submit(task)

if __name__ == '__main__':
main()

带上下文线程池

from concurrent.futures import ThreadPoolExecutor

def task(n):
print("Processing {}".format(n))

def main():
print("Starting ThreadPoolExecutor")
with ThreadPoolExecutor(max_workers=3) as executor:
future = executor.submit(task, (2))
future = executor.submit(task, (3))
future = executor.submit(task, (4))
print("All tasks complete")

if __name__ == '__main__':
main()