Skip to content

Instantly share code, notes, and snippets.

@ivanleoncz
Forked from rahulrajaram/.md
Last active July 31, 2020 03:12
Show Gist options
  • Save ivanleoncz/fe1d961ebf46bda664c9a72f163439fe to your computer and use it in GitHub Desktop.
Save ivanleoncz/fe1d961ebf46bda664c9a72f163439fe to your computer and use it in GitHub Desktop.
Writting to a same file via multiple Threads, using primitive lock.
import threading
import time
global_lock = threading.Lock()
def write_to_file():
while global_lock.locked():
# Give 100ms in order to execute a next loop, if locked.
time.sleep(0.1)
continue
global_lock.acquire()
count = 1
print(f"Running {threading.current_thread().name}...")
with open("output", "a+") as f:
# This will make a Thread very busy, while the others should wait for it
# to finish.
while count < 26:
f.write(f"{threading.current_thread().name}, count {count}\n")
count += 1
global_lock.release()
# Creates 10 threads, invoking write_to_file() through each of them.
threads = []
# Used for creating a custom name for each Thread, instead of using get_ident().
sequence = 1
for i in range(1, 11):
t = threading.Thread(target=write_to_file, name=f"Thread_{sequence}")
threads.append(t)
# This ensures that a KeyboardInterruption will terminate Thread as well.
t.daemon = True
t.start()
sequence += 1
[thread.join() for thread in threads]

Operation

$ python3 write_same_file.py 
Running Thread_1...
Running Thread_4...
Running Thread_3...
Running Thread_9...
Running Thread_7...
Running Thread_6...
Running Thread_10...
Running Thread_2...
Running Thread_8...
Running Thread_5...

Validation

Beside the output, output file has the Thread name which inserted the line, with a number (counter), in order to understand that 25 writings were made by an specific Thread, and only after reaching this number, an othe Thread was able to perform writing operations, and so forth, ensuring that Threads must wait for their turns to write on a same file, while there's a Thread which is already performing writings on it.

ivanleoncz@ilex: ~/git/pythoneggs/threads $ head -n 30 output 
Thread_1, count 1
Thread_1, count 2
Thread_1, count 3
Thread_1, count 4
Thread_1, count 5
Thread_1, count 6
Thread_1, count 7
Thread_1, count 8
Thread_1, count 9
Thread_1, count 10
Thread_1, count 11
Thread_1, count 12
Thread_1, count 13
Thread_1, count 14
Thread_1, count 15
Thread_1, count 16
Thread_1, count 17
Thread_1, count 18
Thread_1, count 19
Thread_1, count 20
Thread_1, count 21
Thread_1, count 22
Thread_1, count 23
Thread_1, count 24
Thread_1, count 25
Thread_4, count 1
Thread_4, count 2
Thread_4, count 3
Thread_4, count 4
Thread_4, count 5

References

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment