问题描述
您好!
我正在尝试使用Queue在线程中实现消息队列。
消息队列有两个操作:
PutMsg(id,msg)#这很简单,只需将id和msg合并为一个
把它放进队列。
WaitMsg(ids,msg)#这是困难的部分
WaitMsg只会获得带有某些ID的msg,但是这个不可能在Queue对象中使用
,因为Queue没有提供方法来查看
消息队列并仅获取匹配的项目。
现在我正在使用一个丑陋的解决方案,获取所有消息并将未使用的
已使用的消息返回队列。但我想要更好的表现。有没有
那里的任何替代品?
这是我目前的解决方案:
def _get_with_ids(self,等待,超时,ids):
= =超时
msg =无
已保存= []
而是的:
start = time.clock()
msg = self.q.get(等待,到)
如果msg和msg [ ids中的'id'']:
休息;
#不是期待的消息,保存它。
saved.append(msg)
to = to - (time.clock() - start)
if to< = 0:
break
#将保存的消息放回队列
for m in saved:
self.q.put(m,True)
返回信息
br,Terry
Hello!
I''m trying to implement a message queue among threads using Queue. The
message queue has two operations:
PutMsg(id, msg) # this is simple, just combine the id and msg as one
and put it into the Queue.
WaitMsg(ids, msg) # this is the hard part
WaitMsg will get only msg with certain ids, but this is not possible
in Queue object, because Queue provides no method to peek into the
message queue and fetch only matched item.
Now I''m using an ugly solution, fetch all the messages and put the not
used ones back to the queue. But I want a better performance. Is there
any alternative out there?
This is my current solution:
def _get_with_ids(self,wait, timeout, ids):
to = timeout
msg = None
saved = []
while True:
start = time.clock()
msg =self.q.get(wait, to)
if msg and msg[''id''] in ids:
break;
# not the expecting message, save it.
saved.append(msg)
to = to - (time.clock()-start)
if to <= 0:
break
# put the saved messages back to the queue
for m in saved:
self.q.put(m, True)
return msg
br, Terry
推荐答案
我刚发现Queue是用Python编写的,也许我可以覆盖它。
I just found that Queue is written in Python, maybe I can override it.
你可以尝试一个包含队列的defaultdict,每个消息ID一个队列。
或者你可以实现自己的线程安全的LookAheadQueue类。
David
You could try a defaultdict containing queues, one queue per message ID.
Or you could implement your own thread-safe LookAheadQueue class.
David
那里你有很多方法可以解决这个问题,这两个是我想到的第一个
。
另一个想法是拥有多个队列,每个线程一个或每个
消息类型group。生产者线程推送到相应的
队列(通过智能PutMsg函数),并且消费者从他们感兴趣的队列中拉出
线程并忽略
其他人。
如果您的应用程序线程严重,您可以看看Stackless
Python:
David。
There are a lot of ways you could go about it, those 2 were the first
that came to mind.
Another idea would be to have multiple queues, one per thread or per
message type "group". The producer thread pushes into the appropriate
queues (through an intelligent PutMsg function), and the consumer
threads pull from the queues they''re interested in and ignore the
others.
If your apps are heavily threaded you might take a look at Stackless
Python: http://www.stackless.com/
David.
这篇关于有关队列对象的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!