Skip to content

Instantly share code, notes, and snippets.

@andreaschandra
Created June 7, 2020 07:49
Show Gist options
  • Save andreaschandra/6c9765d77ae6c49bea01a92d0f7542da to your computer and use it in GitHub Desktop.
Save andreaschandra/6c9765d77ae6c49bea01a92d0f7542da to your computer and use it in GitHub Desktop.
import time
import concurrent.futures
from itertools import compress
start = time.perf_counter()
storage = []
tokens = [True] * 2
def get_free_token(tokens):
idx_tokens = list(compress(range(len(tokens)), tokens))
if len(idx_tokens) > 0:
return idx_tokens[0]
else:
return None
def do_something(seconds, idx_token):
print(f'\tsleeping {seconds} seconds using token {idx_token}')
time.sleep(seconds)
storage.append(seconds)
print(f'Done Sleeping in {seconds} using token {idx_token}')
tokens[idx_token] = True
def submission(executor, num, idx_token):
print("\tidx token", idx_token, "is used")
executor.submit(do_something, num, idx_token)
with concurrent.futures.ThreadPoolExecutor() as executor:
data = [3,1,5,3,1,1]
for num in data:
print("tokens status", tokens)
while True:
idx_token = get_free_token(tokens)
if idx_token is not None:
tokens[idx_token] = False
status = submission(executor, num, idx_token)
print("\tafter submission tokens", tokens)
break
print(storage)
stop = time.perf_counter()
print(f'finished all process in {round(stop-start, 2)} seconds')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment