【问题标题】:Multiple threads with the same coroutine?具有相同协程的多个线程?
【发布时间】:2015-01-07 08:21:38
【问题描述】:

我可以运行多个线程来运行同一个协程副本吗?

例如,如果我将线程函数从 tutorial 更改为

@coroutine
def threaded(count, target):
    messages = Queue()
    def run_target():
        while True:
            item = messages.get()
            if item is GeneratorExit:
                target.close()
                return
            else:
                target.send(item)

    for i in xrange(count):
        Thread(target=run_target).start()

    try:
        while True:
            item = (yield)
             messages.put(item)
     except GeneratorExit:
         messages.put(GeneratorExit)

这真的有效吗?如何验证它是否正常工作?

【问题讨论】:

    标签: python multithreading coroutine


    【解决方案1】:

    我想我已经解决了,我需要将函数更改为类似这样才能正常工作

    @coroutine
    def _threaded(self, count, target_func):
        """
        Given a target coroutine, spawn $count threads to run copies of them. In
        order to properly use this, do not call the coroutine before calling this,
        e.g.
    
            @coroutine
            def foo(self):
                ...
    
            def bar(self):
                ...
                self._threaded(10, self.foo)    # <- do not call self.foo,
                                                # just the reference
    
        @param count        The number of threads to spawn
        @param target_func  The reference to the target coroutine
        @returns            The subnet mask
        """
        result = None
    
        messages = Queue()
    
        def default_target_run(index):
            target = target_func()
            while True:
                item = messages.get()
                if item is GeneratorExit:
                    target.close()
                    return
                else:
                    target.send({'index': index, 'item': item})
    
        # ensure code is testable
        target_run = default_target_run
        try:
            target_run = self._threaded.target_run
        except AttributeError:
            pass
    
        result = ThreadPool(count).map_async(target_run, range(count))
    
        try:
            while True:
                item = (yield)
                messages.put(item)
        except GeneratorExit:
            # allow all threads to quit
            # by making sure all of them receives the exit message
            for i in xrange(count):
                messages.put(GeneratorExit)
    
        result.ready()
    

    【讨论】:

      猜你喜欢
      • 2018-03-10
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2013-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多