Thread batch with timeout - return values in dict
- import threadingbatch
- add the decorator @threadingbatch.thread_capture to your function
- add *args, **kwargs to your function
- create a list of lists with all function calls
- call threadingbatch.start_all_threads
- get the results from threadingbatch.results
$ pip install threadingbatch
from kthread_sleep import sleep
import threadingbatch
import random
@threadingbatch.thread_capture
def test(
testnumber, *args, **kwargs
):
print(f"start {testnumber}")
sleep(1)
v = random.randrange(1, 30)
print(f"end {testnumber}")
return v
flist = []
for ini, k in enumerate(range(20)):
flist.append(
[
test,
(),
{"testnumber": ini},
f"function_{str(ini)}",
]
)
flistt = threadingbatch.start_all_threads(
flist,
threadtlimit=5,
timeout=4,
sleepafterkill=0.02,
sleepafterstart=0.02,
ignore_exceptions=False,
verbose=False,
)
while not threadingbatch.results[
"done"
]:
pass
sleep(0.1)
print(threadingbatch.results)