Python:管理由其他线程通知的事件的线程

2024-03-29 10:38:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用Python开发一个多线程应用程序。特别是,在这个应用程序中,一个线程应该能够生成一个应该通知一个(或多个)线程的事件;接收事件通知的线程应该中断它们的执行并运行一个特定的函数。在这个服务函数的末尾,他们应该返回到事件生成之前所做的事情。在

为了做这样的事情,我考虑使用某种发布/订阅模块。我发现了一个非常容易使用的:PyPubSub。您可以找到here一个关于如何使用它的非常简单的示例。在

顺便说一句,当我开始使用它时,我意识到它确实符合我的要求,但只有当你只使用过程时。如果有更多的线程,它会挂起整个进程(因此,其中的所有线程)来运行特定的例程。这实际上不是我想要的行为。不幸的是,我无法将我的应用程序从多线程更改为多进程。在

你知道有什么模块可以帮助我在多线程应用程序中做我想做的事情吗?谢谢。在


Tags: 模块函数应用程序示例here进程过程事件
1条回答
网友
1楼 · 发布于 2024-03-29 10:38:38

在python中,除了通过多处理模块之外,没有真正的并发性,因为GIL不是图片的一部分。在

要执行的操作需要一个事件循环,在该循环中检查事件队列并根据需要进行分派。Pypubsub可能会让您的生活更轻松,但可能会为您想要的做得太多(正如pubsub的作者所说的那样:)考虑到mp模块如何提供多个进程的无缝集成,如果您真正需要并发,是否真的有理由不使用它?在

您希望事件从任何线程传递到一个或多个线程这一事实表明,您可以使用任何线程都可以发送到的共享post队列,这些数据指示哪个事件类型和事件数据。另外,每个线程都有一个消息队列:线程发布到共享的发布队列,主进程事件循环检查发布队列,并根据需要将事件复制到各个线程消息队列。每个线程必须定期检查其队列并进行处理,删除已处理的事件。每个线程可以为特定事件订阅主进程。在

下面是3个互相发送消息的辅助线程的示例:

from multiprocessing import Process, Queue, Lock
from Queue import Empty as QueueEmpty
from random import randint


def log(lock, threadId, msg):
    lock.acquire()
    print 'Thread', threadId, ':', msg
    lock.release()


def auxThread(id, lock, sendQueue, recvQueue, genType):
    ## Read from the queue
    log(lock, id, 'starting')
    while True:
        # send a message (once in a while!)
        if randint(1,10) > 7:
            event = dict(type = genType, fromId = id, val = randint(1, 10) )
            log(lock, id, 'putting message type "%(type)s" = %(val)s' % event)
            sendQueue.put(event)

        # block until we get a message:
        maxWait = 1 # second
        try:
            msg = recvQueue.get(False, maxWait)
            log(lock, id, 'got message type "%(type)s" = %(val)s from thread %(fromId)s' % msg)
            if (msg['val'] == 'DONE'):
                break
        except QueueEmpty:
            pass

    log(lock, id, 'done')


def createThread(id, lock, postOffice, genType):
    messagesForAux = Queue()
    args = (id, lock, postOffice, messagesForAux, genType)
    auxProc = Process(target=auxThread, args=args)
    auxProc.daemon = True
    return dict(q=messagesForAux, p=auxProc, id=id)


def mainThread():
    postOffice = Queue()   # where all threads post their messages
    lock = Lock() # so print can be synchronized

    # setup threads:
    msgThreads = [
        createThread(1, lock, postOffice, 'heartbeat'),
        createThread(2, lock, postOffice, 'new_socket'),
        createThread(3, lock, postOffice, 'keypress'),
    ]

    # identify which threads listen for which messages
    dispatch = dict(
        heartbeat  = (2,),
        keypress   = (1,),
        new_socket = (3,),
    )

    # start all threads
    for th in msgThreads:
        th['p'].start()

    # process messages
    count = 0
    while True:
        try:
            maxWait = 1 # second
            msg = postOffice.get(False, maxWait)
            for threadId in dispatch[msg['type']]:
                thObj = msgThreads[threadId - 1]
                thObj['q'].put(msg)
            count += 1
            if count > 20:
                break

        except QueueEmpty:
            pass

    log(lock, 0, "Main thread sending exit signal to aux threads")
    for th in msgThreads:
        th['q'].put(dict(type='command', val='DONE', fromId=0))

    for th in msgThreads:
        th['p'].join()
        log(lock, th['id'], 'joined main')
    log(lock, 0, "DONE")


if __name__ == '__main__':
    mainThread()

您完全正确,这个描述与pypubsub功能有相似之处,但是您只使用了pypubsub的一小部分,我认为您所做的工作中最复杂的部分是两种类型的队列,pypubsub对解决这个问题没有多大帮助。一旦队列系统使用mp module工作(如我的示例所示),就可以引入pypubsub并发布/排队其消息,而不是自己植入一个事件。在

相关问题 更多 >