由于将在接收方线程中调用侦听器,因此,如果要在其他线程(例如主线程)中处理消息,则应执行线程切换。
线程切换的一个简单示例是使用具有锁定功能的共享变量,并在接收方线程接收到消息时更新该变量。并且,在另一个线程中读取该变量,但是您需要使用适当的同步机制来确保您不覆盖消息,并且不会遇到死锁。
这是在锁定中使用某些全局变量的示例代码。
rcvd_msg = Nonelock = thread.Condition()# executed in the main threadwith lock: while rcvd_msg == None: lock.wait() # read rcvd_msg rcvd_msg = None lock.notifyAll()class Listener(ConnectionListener): def on_message(self, headers, message): # executed in the receiver thread global rcvd_msg, lock with lock: while rcvd_msg != None: lock.wait() rcvd_msg = message lock.notifyAll()
希望有帮助!!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)