Python线程卡住



我正在尝试从一个名为CameraProcessing的线程切换到另一个名为的线程ServerKeypoints,反之亦然。准确地说,CameraProcessing改变一个全局变量VALUEwhileServerKeypoints通过websocket发送给客户端来消耗全局值。为了保护全局变量,我使用了条件机制.

我有两个问题:

  1. 在某个时刻,脚本卡住了,线程不能继续前进
  2. websocket客户端不接收通过websocket发送的数据

这两个线程位于名为main_server.py的脚本中(我知道这不是最好的主意,最好将这些线程拆分到不同的文件中)。

main_server.py

import threading
import asyncio
import websockets
condition = threading.Condition()
VALUE = 0
FLAG = 0

class ServerKeypoints(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
async def communicate(self, websocket):
global VALUE
global FLAG
while True:
condition.acquire()
if FLAG == 1:
FLAG = 0
print(f"SERVER VAL: {VALUE}")
await websocket.send(f"{VALUE}")
condition.notify_all()
else:
condition.wait()
condition.release()
async def main(self,):
async with websockets.serve(self.communicate, "localhost", 9998):
await asyncio.Future()  # run forever
def run(self):
asyncio.run(self.main())

class CameraProcessing(threading.Thread):
def __init__(self) -> None:
threading.Thread.__init__(self)

def run(self):
global VALUE
global FLAG
while True:
condition.acquire()
if FLAG == 0:
VALUE += 1
print(f"CAMERA VAL: {VALUE}")
FLAG = 1
condition.notify_all()
else:
condition.wait()
condition.release()

,client.py以如下方式书写:

import websocket
def on_message(wsapp, message):
message = message
print(message)
wsapp = websocket.WebSocketApp("ws://localhost:9998", on_message=on_message)
while True:
wsapp.run_forever()

在Visual Studio Code终端中,我得到如下结果:

CAMERA VAL: 20301
SERVER VAL: 20301
CAMERA VAL: 20302
SERVER VAL: 20302
CAMERA VAL: 20303
SERVER VAL: 20303
CAMERA VAL: 20304
SERVER VAL: 20304
CAMERA VAL: 20305
SERVER VAL: 20305
CAMERA VAL: 20306
SERVER VAL: 20306
CAMERA VAL: 20307
SERVER VAL: 20307
CAMERA VAL: 20308
SERVER VAL: 20308
CAMERA VAL: 20309
SERVER VAL: 20309
CAMERA VAL: 20310
SERVER VAL: 20310
CAMERA VAL: 20311
SERVER VAL: 20311
CAMERA VAL: 20312
SERVER VAL: 20312
CAMERA VAL: 20313
SERVER VAL: 20313

但它没有向前。

正如michael Butscher在评论中建议的那样,我再次尝试了websockets提供的客户端脚本。模块和我已经修改了如下方式:

import asyncio
import websockets
async def receive():
while True:
try:
async with websockets.connect("ws://localhost:9998", ping_interval=None) as websocket:
msg = await websocket.recv()
print(f"{msg}")
except:
continue
if __name__ == "__main__":
asyncio.run(receive())

现在不粘了

我知道组合asyncthread不是一个好主意,但是如果你有其他的建议,我将很高兴阅读它们。

我使用线程是因为它们共享全局变量VALUE,为了保护它,我使用了线程锁,如Condition。

好的,但是你不需要为了使用全局变量而创建线程。你的ServerKeypoints线程和你的CameraProcessing线程从来不会并发地做任何有趣的事情,所以为什么不让一个线程做这件事呢?

async def communicate(self, websocket):
global VALUE
while True:
VALUE += 1
print(f"CAMERA VAL: {VALUE}")
print(f"SERVER VAL: {VALUE}")
await websocket.send(f"{VALUE}")

去掉condition,去掉FLAG,去掉线程。这要简单得多,而且(我很确定)它将做与示例代码相同的事情。

最新更新