Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python and threading don't mix
#!/usr/bin/python3
# Write to a tarball from multiple threads to demonstrate corruption.
import tarfile, threading, io
N_THREADS = 8
def append_tar(tarf, val):
tf = tarfile.TarInfo(name="{}".format(val))
# Generate an entry with the unique byte
# repeated so it's easy to see intermixed content.
tf.size = 4096
buf = bytearray([val for x in range(tf.size)])
tarf.addfile(tf, io.BytesIO(buf))
tarf = tarfile.open("out.tar", mode='w')
threads = []
for x in range(N_THREADS):
t = threading.Thread(target=lambda: append_tar(tarf, x))
t.start()
threads.append(t)
for t in threads:
t.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment