| 1 |
#!/usr/bin/env python3 |
| 2 |
import threading |
| 3 |
from concurrent.futures import ThreadPoolExecutor |
| 4 |
|
| 5 |
from msgpack import Packer |
| 6 |
|
| 7 |
|
| 8 |
def run_threaded( |
| 9 |
func, |
| 10 |
num_threads=8, |
| 11 |
pass_count=False, |
| 12 |
pass_barrier=False, |
| 13 |
outer_iterations=1, |
| 14 |
prepare_args=None, |
| 15 |
): |
| 16 |
"""Runs a function many times in parallel""" |
| 17 |
for _ in range(outer_iterations): |
| 18 |
with ThreadPoolExecutor(max_workers=num_threads) as tpe: |
| 19 |
if prepare_args is None: |
| 20 |
args = [] |
| 21 |
else: |
| 22 |
args = prepare_args() |
| 23 |
if pass_barrier: |
| 24 |
barrier = threading.Barrier(num_threads) |
| 25 |
args.append(barrier) |
| 26 |
if pass_count: |
| 27 |
all_args = [(func, i, *args) for i in range(num_threads)] |
| 28 |
else: |
| 29 |
all_args = [(func, *args) for i in range(num_threads)] |
| 30 |
try: |
| 31 |
futures = [] |
| 32 |
for arg in all_args: |
| 33 |
futures.append(tpe.submit(*arg)) |
| 34 |
finally: |
| 35 |
if len(futures) < num_threads and pass_barrier: |
| 36 |
barrier.abort() |
| 37 |
for f in futures: |
| 38 |
f.result() |
| 39 |
|
| 40 |
|
| 41 |
def test_multithread_packing(): |
| 42 |
output = [] |
| 43 |
test_data = "abcd" * 10_000_000 |
| 44 |
packer = Packer() |
| 45 |
|
| 46 |
def closure(b): |
| 47 |
data = packer.pack(test_data) |
| 48 |
output.append(data) |
| 49 |
b.wait() |
| 50 |
|
| 51 |
run_threaded(closure, num_threads=10, pass_barrier=True, pass_count=False) |