Python and threading don't mix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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