【问题标题】:Counter across threads跨线程计数器
【发布时间】:2013-12-21 12:26:10
【问题描述】:

结合使用队列和线程。它是这样的:

import threading
import Queue

# Message sender
def msg_send(msg):
    # Relay packed message

# Thread loop
def thread_func(queue):
    while 1:
        # Read stdin
        # Parse
        # On error send error message with new ID   <-- ID
        # On OK put ratified message into queue
        queue.put(msg)

# Class with main loop
class SomeApplication(options):
    def __init__(self, options):
         self.option1 = ...

    def queue_process(self):
        if self.queue.empty()
            return
        while not self.queue.empty():
            # Process message
            # etc

        # Post process actions
        # Send message with new ID on occasion.     <--- ID

    def loop(self, queue):
         while self.run:
             # do stuff
             # Send message using ID                <--- ID
             self.queue_process()
             time.sleep(self.sleep_time)


def Main():
    queue  = Queue.Queue()   # New Queue

                             # Declare thread
    thread = threading.Thread(target = thread_func, args = (queue))
    thread.daemon = True     # Daemon
    thread.start()           # Start thread

    app = SomeClass(options) # New instance of SomeClass

    app.loop(queue)          # Main loop
    app.quit()               # Tidy up app things.
    quit(thread)             # Closing thread and tidying up.

现在,我想添加一个计数器作为消息 ID。如:

 message = {
     'id'   : ++counter,
     'data' : data
 }

 msg = pack_message(message)
 msg_send(msg)

如果消息是回复,我重用请求 ID,否则我使用计数器生成下一个 ID。我希望它是连续的,因为它还可以用作 messages sent 计数器。

我可以添加一个全局变量作为计数器并在msg_send() 中使用它,但是在调用该函数时,消息被打包(内部带有 ID)。包装内容不同,有时不重新包装。

如何同时为线程(有时读取传入和发送消息)和具有公共计数器的类函数提供服务?

可以使用全局变量吗?有没有更好的办法?我应该朝以下方向做点什么:

def id_gen():
    id_gen.counter += 1
    return id_gen.counter

id_gen.counter = 0

Hrmf。这解释得很尴尬,希望你明白我的意思。

【问题讨论】:

  • 看看这个答案中的线程安全计数器代码。 stackoverflow.com/questions/1717393/… 共享一个实例将是一个非常可行的解决方案。当然,通过序列化访问会付出性能损失。
  • @stephbu:很好,看起来差不多。 知道“谢谢”在 cmets 中是不受欢迎的,但在这种情况下,我会留下一个。

标签: python multithreading


【解决方案1】:

如果我理解正确,您希望全局变量可以在多个线程中访问。这样做的问题是你必须一次“保护”你的变量免受多次访问,这就是你可以用 Monitor 类做的事情,它会根据你使用的语言而有所不同,我认为全局变量是可以接受的解决方案。

【讨论】:

  • 是的,我想要一个使用 Python 的通用线程安全计数器。 stephbu 在 Q 下面的评论看起来可以完成任务。
猜你喜欢
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 2016-05-02
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多