Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import threading
- import time
- mutex = threading.Lock()
- sum = 0
- sum2 = 0
- def safe_race_thread1():
- global sum
- for i in range(0,1000):
- mutex.acquire()
- tmp = sum
- time.sleep(0)
- tmp += i
- time.sleep(0)
- sum = tmp
- mutex.release()
- def safe_race_thread2():
- global sum
- for i in range(1, 1000):
- mutex.acquire()
- tmp = sum
- time.sleep(0)
- tmp -= i
- time.sleep(0)
- sum = tmp
- mutex.release()
- def unsafe_race_thread1():
- global sum2
- for i in range(0, 1000):
- tmp = sum2
- time.sleep(0)
- tmp += i
- time.sleep(0)
- sum2 = tmp
- def unsafe_race_thread2():
- global sum2
- for i in range(1, 1000):
- tmp = sum2
- time.sleep(0)
- tmp -= i
- time.sleep(0)
- sum2 = tmp
- thread1 = threading.Thread(target = safe_race_thread1)
- thread2 = threading.Thread(target = safe_race_thread2)
- thread3 = threading.Thread(target = unsafe_race_thread1)
- thread4 = threading.Thread(target = unsafe_race_thread2)
- thread1.start()
- thread2.start()
- thread3.start()
- thread4.start()
- thread1.join()
- thread2.join()
- thread3.join()
- thread4.join()
- print ("Результат при работе с блокировкой", sum)
- print ("Результат без блокировки", sum2)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement