我不明白为什么只有一个线程时要使用线程锁。以下是我在网上看到的代码。难道线程锁不是仅在除主线程外有两个以上的线程时使用吗?
我不明白为什么在这行代码中使用了线程锁。
如果没有使用线程锁,会发生什么?
import socket
import threading
tLock = threading.Lock()
shutdown = False
def receving(name, sock):
while not shutdown:
try:
tLock.acquire()
while True:
data, addr = sock.recvfrom(1024)
print str(data)
except:
pass
finally:
tLock.release()
host = '127.0.0.1'
port = 0
server = ('127.0.0.1',5000)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
s.setblocking(0)
rT = threading.Thread(target=receving, args=("RecvThread",s))
rT.start()
alias = raw_input("Name: ")
message = raw_input(alias + "-> ")
while message != 'q':
if message != '':
s.sendto(alias + ": " + message, server)
tLock.acquire()
message = raw_input(alias + "-> ")
tLock.release()
time.sleep(0.2)
shudown = True
rT.join()
s.close()
我不明白为什么在这行代码中使用了线程锁。
tLock.acquire()
message = raw_input(alias + "-> ")
tLock.release()
如果没有使用线程锁,会发生什么?