我正在尝试使用多线程在python中编写代码,该代码在单个程序文件中运行UDP服务器端和UDP客户端。我需要确保线程是同步的。
我的代码的问题(据我所知)是当thread1运行时,它获取锁,因为thread1的run()方法运行包含永久while循环的serverSide()方法,thread1不释放锁定,因此程序卡住了。
任何人都可以帮助我同步线程,同时确保服务器和客户端正常运行
import threading
import time
import sys
from datetime import datetime
from socket import *
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
serverSide()
# Free lock to release next thread
threadLock.release()
class myThread1 (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
clientSide()
# Free lock to release next thread
threadLock.release()
def serverSide():
serverPort = 44000
serverIP = '192.168.0.0'
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind((serverIP,serverPort))
print ("SERVER HERE!\nThe server is ready to receive")
while 1:
message, clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage, clientAddress)
def clientSide():
serverIP = "192.168.0.0"
serverPort = 44000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = raw_input("CLIENT HERE!\nInput lowercase sentence:")
clientSocket.sendto(message.encode(),(serverIP, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print(modifiedMessage) # print the received message
clientSocket.close() # Close the socket
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread1(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
答案 0 :(得分:1)
除同步部分外,您的代码工作正常。
所以问题在于,有一个threadLock = threading.Lock()
曾经被另一个线程无法获取的两个线程中的任何一个获得。
一旦线程获得它,它就不会释放它直到它的工作完成。除非另一个线程启动并运行,否则它的工作无法完成。另一个线程正在等待第一个线程释放锁定。
您已经人为地设法在您的代码中引发竞争条件,这完全不需要。我只是用螺纹锁取下整个零件并且工作正常。除了我不得不打断程序结束它。
import threading
import time
import sys
from datetime import datetime
from socket import *
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
# Get lock to synchronize threads
# threadLock.acquire()
serverSide()
# Free lock to release next thread
# threadLock.release()
class myThread1 (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print ("Starting " + self.name)
# Get lock to synchronize threads
# threadLock.acquire()
clientSide()
# Free lock to release next thread
# threadLock.release()
def serverSide():
serverPort = 44000
serverIP = '127.0.0.1'
serverSocket = socket(AF_INET, SOCK_DGRAM)
serverSocket.bind((serverIP,serverPort))
print ("SERVER HERE!\nThe server is ready to receive")
while 1:
message, clientAddress = serverSocket.recvfrom(2048)
modifiedMessage = message.upper()
serverSocket.sendto(modifiedMessage, clientAddress)
def clientSide():
serverIP = "127.0.0.1"
serverPort = 44000
clientSocket = socket(AF_INET, SOCK_DGRAM)
message = input("CLIENT HERE!\nInput lowercase sentence:")
clientSocket.sendto(message.encode(),(serverIP, serverPort))
modifiedMessage, serverAddress = clientSocket.recvfrom(2048)
print("received", modifiedMessage) # print the received message
clientSocket.close() # Close the socket
# threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread1(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print ("Exiting Main Thread")
输出:
Starting Thread-1
Starting Thread-2
SERVER HERE!
The server is ready to receive
CLIENT HERE!
Input lowercase sentence:viki
received b'VIKI'
注意:
我正在尝试使用多线程在python中编写代码,该代码在单个程序文件中运行UDP服务器端和UDP客户端。我需要确保线程是同步的。
在大多数情况下,客户端服务器体系结构不应该同步。 Google服务器和我的浏览器未同步。并且它们不应该适用于您的代码。原因是服务器应该独立于客户端运行而不是运行。
客户端应该独立于服务器是否运行而运行。如果服务器关闭,客户端请求将失败。但它仍然应该运行。