Skip to content

Instantly share code, notes, and snippets.

@iamsardorbek
Created February 13, 2021 12:30
Show Gist options
  • Save iamsardorbek/ae837e770c4d49eda071acbf55b92c32 to your computer and use it in GitHub Desktop.
Save iamsardorbek/ae837e770c4d49eda071acbf55b92c32 to your computer and use it in GitHub Desktop.
OS assignment on threads (problem solved)
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