Created
February 13, 2021 12:30
-
-
Save iamsardorbek/ae837e770c4d49eda071acbf55b92c32 to your computer and use it in GitHub Desktop.
OS assignment on threads (problem solved)
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
import threading | |
import time | |
var = 0 | |
mutex = threading.Lock() | |
def runner0(): | |
i = 0 | |
global var | |
while i < 1000000: | |
mutex.acquire() | |
var += 1 | |
mutex.release() | |
i += 1 | |
print("Incrementation ended, var = %d" % var) | |
return | |
def runner1(): | |
i = 0 | |
global var | |
while i < 1000000: | |
mutex.acquire() | |
var -= 1 | |
mutex.release() | |
i += 1 | |
print("Decrementation ended, var = %d" % var) | |
return | |
# MAIN PART HERE # | |
start_time_seconds = time.time() | |
thread0 = threading.Thread(target=runner0, args=(), daemon=True) | |
thread1 = threading.Thread(target=runner1, args=(), daemon=True) | |
thread0.start() | |
thread1.start() | |
thread0.join() | |
thread1.join() | |
print("var = %d" % var) | |
print("Code took %.4f seconds to execute" % (time.time() - start_time_seconds)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment