I have a background thread that occasionally needs keyboard input. However, the main thread also reads input from the keyboard. When I call input() the main thread gets the input. I have tried using locks, but they do not work for me.
Main process (only part of the code):
def smth(aff):
af = aff
lock = threading.Lock()
print(lock)
Peer.setlock(lock)
while True:
lock.acquire(blocking=True, timeout=-1)
inp = input()
parse(inp)
lock.release()
Thread code:
global lock
def setlock(j):
print("Setting lock ", j)
global lock
lock = j
print("Lock status: ", lock.locked())
success = lock.acquire(blocking=True, timeout=-1)
print(success)
print("You are recieving a file, type y to confirm saving:")
print(lock)
if input() == "y":
path = ""
print("Input path:")
path = input()
if os.path.isfile(path):
print("File already exists. Type y to confirm:")
if not input()=="y":
return
handle = open(path, "wb")
filewriters[transferID] = filewg(handle, numberOfPackets)
filewriters[transferID].send(None)
lock.release()
print(lock)
The entire code resides here.
I just wrote another minimal example, and locks seem to work here: import threading
lock = threading.Lock()
def th():
while True:
lock.acquire(blocking=True, timeout=-1)
print("Thread prints ", input())
lock.release()
tic = threading.Thread(target=th)
tic.start()
while True:
lock.acquire(blocking=True, timeout=-1)
print("Main prints ", input())
lock.release()