import concurrent.futures # Define function to calculate square of a number def square(n): return n**2 # Create a ThreadPoolExecutor with 4 threads with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: # Map the square function to a range of numbers results = executor.map(square, range(10)) # Print the results for res in results: print(res)
import concurrent.futures import requests # Define function to download a file and return its content def download_file(url): response = requests.get(url) return response.content # Create a ThreadPoolExecutor with 4 threads with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor: # Map the download_file function to a list of URLs results = executor.map(download_file, [ 'https://www.example.com/file1', 'https://www.example.com/file2', 'https://www.example.com/file3' ]) # Print the results (file contents) for res in results: print(res)In the above example, we define a function download_file() that takes a URL, downloads the file from that URL, and returns the file content. We create a ThreadPoolExecutor with 4 threads, and then use the map() function to apply the download_file() function to a list of URLs. The map() function returns an iterator which we can use to obtain the file contents for each URL. Finally, we print the file contents. Both of these examples use the concurrent.futures package library in Python.