Create 2 writers and 2 readers services with different period of launching. Writers periodically change two counters the sum of which always should be 100. The readers show that counter’s value. Prove that without synchronization the sum of two counters is not always 100.
git clone [email protected]:danielyandev/python-lock-test.git
pip install -r requirements.txt
Prepare .env file
cp .env.example .env
Prepare counter files
cp counter.txt.example counter1.txt
cp counter.txt.example counter2.txt
Set USE_FILE_LOCK variable in .env file one of these values: {true, 1} to use file locking, otherwise operations with file will be performed without locking
python main.py
Running script with and without locking, we can see different results
Using locks will result in having correct result: each time the sum will be equal to 100, because files are locked during write/read processes and no other process can access it.
If we don't use locks we face such cases when file was overwritten by 2 processes simultaneously and the final result can't be predicted.
Without synchronization the sum of two counters is not always 100. To have predictable results in multithreading applications, it is important to use file locking.