Skip to content

Instantly share code, notes, and snippets.

@adminy
Created October 12, 2020 09:52
Show Gist options
  • Save adminy/5c5ce1d2230fe54af1b39f73bebe5a4c to your computer and use it in GitHub Desktop.
Save adminy/5c5ce1d2230fe54af1b39f73bebe5a4c to your computer and use it in GitHub Desktop.
How Not to write multi-threaded python code
import _thread
from time import sleep
def fmap(out, a, b): out.append(a * b)
def threading(pairs):
out = []
for (a, b) in pairs:
thread = _thread.start_new_thread(fmap, (out, a, b, ))
return out
def make_pairs(a):
if len(a) % 2 != 0:
a.append(1)
pairs = []
for i in range(0, len(a), 2):
pairs.append((a[i], a[i+1]))
return pairs
def factorial(N):
pairs = make_pairs([x for x in range(1, N + 1)])
while len(pairs) != 1:
out = threading(pairs)
while len(out) != len(pairs):
sleep(0.01)
pairs = make_pairs(out)
print(pairs)
return pairs[0][0] * pairs[0][1]
if __name__ == '__main__':
print(factorial(10))
import _thread
from time import sleep
def slice(text, chunk_size):
chunks = []
for i in range(0, len(text), chunk_size):
chunks.append(text[i:i+chunk_size])
return chunks
def count_letters(text, letter, threads):
TOTALS = []
def count_chunk(chunk, letter):
TOTALS.append(sum([c == letter for c in chunk]))
length = len(text)
chunk_size = length // threads
chunks = slice(text, chunk_size)
for chunk in chunks:
_thread.start_new_thread(count_chunk, (chunk, letter, ))
while len(TOTALS) != len(chunks):
sleep(0.01)
return sum(TOTALS)
if __name__ == '__main__':
print(count_letters("there are so many letter e here", "e", 8))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment