跨线程计数

问题描述 投票:0回答:1

将Queue与线程结合使用。它是这样的:

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)

如果message是回复,我重用请求ID,否则我使用计数器生成下一个ID。我希望它是顺序的,因为它然后也作为一个消息发送计数器。

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

我如何同时提供线程,有时读取传入+发送消息,以及使用公共计数器的类函数?

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

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

id_gen.counter = 0

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

python multithreading
1个回答
1
投票

如果我理解正确,你想要在多个线程中访问全局变量。这个问题是你必须一次“保护”你的变量不受多次访问的影响,这就是你可以用Monitor类做的事情,这取决于你使用哪种语言,我觉得全局变量是可以接受的解。

© www.soinside.com 2019 - 2024. All rights reserved.