Created
October 17, 2019 15:44
-
-
Save kleviscipi/3213d32ccb1ea2de14b998dff731a7d4 to your computer and use it in GitHub Desktop.
Using a Lock for passing the race conditions during a multithread egzecution
This file contains hidden or 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
| from threading import Thread,Lock | |
| import sys | |
| """ | |
| Mutual Exlusion: | |
| When tow concurrent threads or processes want to use a shared resource, | |
| that means one thread block the concurrent since its is using that resource | |
| Process A | |
| Process B | |
| Resource X | |
| ------- Process A -> started ||||||||||||||||||||||| ended | |
| Resource X : A in Egzecution using X B in Egzecution using X | |
| ------- Process B -> *********************** ||||||||||||||||||||||||| ended | |
| _______WAIT A TIME_____ | |
| """ | |
| """ | |
| Lock, is a implmentation of mutual exlusion. | |
| When tow concurrent threads want to access at shared resources the first should graph a lock before use that resource. | |
| After lock is in use by one thread, last concurrent should wait since that lock is released by the first thread. | |
| A lock is used just by one thread in one time. | |
| Deadlock, happens when the program is blocked, because at the same concurrent(thread) A is waiting for B and either concurrent B is waiting for A | |
| Race Conditions, happens when a shared resource is accessed at the same time by tow parallel threads/processes and it is | |
| updated by them and that's means that resource is not protected by a lock | |
| """ | |
| #Race conditions | |
| COUNT = 1000000 | |
| x = 0 | |
| L = Lock() | |
| def inc(): | |
| L.acquire() | |
| global x | |
| try: | |
| for _ in range(COUNT): | |
| x += 1 | |
| finally: | |
| print("First Inc: {}".format(x) ) | |
| L.release() | |
| def dec(): | |
| L.acquire() | |
| global x | |
| try: | |
| for _ in range(COUNT): | |
| x -= 1 | |
| finally: | |
| print("Second Dec: {}".format(x) ) | |
| L.release() | |
| if __name__ == "__main__": | |
| th_1 = Thread(target=inc) | |
| th_2 = Thread(target=dec) | |
| th_2.start() | |
| th_1.start() | |
| th_2.join() | |
| th_1.join() | |
| print("Final Result: {}".format(x) ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment