December 2018
Beginner to intermediate
796 pages
19h 54m
English
In this example, we amend the sort function once again, so that, after the initial division into chunks, it spawns a thread per part. Each thread uses the single-threaded version of the algorithm to sort its part, and then at the end we use the multi-merge technique to calculate the final result. Translating into Python:
# ms/algo/mergesort_thread.pyfrom functools import reducefrom math import ceilfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom .mergesort import sort as _sort, mergedef sort(v, workers=2): if len(v) == 0: return v dim = ceil(len(v) / workers) chunks = (v[k: k + dim] for k in range(0, len(v), dim)) with ThreadPoolExecutor(max_workers=workers) as executor: futures = [ executor.submit(_sort, ...
Read now
Unlock full access