Python 中是否有来自 ObjectiveC 的 NSOperationQueue 之类的东西? [英] Is there something like NSOperationQueue from ObjectiveC in Python?

查看:57
本文介绍了Python 中是否有来自 ObjectiveC 的 NSOperationQueue 之类的东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究 Python 的并发选项.由于我是一名 iOS/macOS 开发人员,如果在 python 中有类似 NSOperationQueue 的东西,我会发现它非常有用.

I'm looking into concurrency options for Python. Since I'm an iOS/macOS developer, I'd find it very useful if there was something like NSOperationQueue in python.

基本上,它是一个队列,您可以向其中添加操作(每个操作都是具有 run 方法的操作派生类来实现),这些操作可以串行或并行执行,或者理想情况下可以对操作设置各种依赖项(即某些操作取决于正在执行的其他操作才能开始).

Basically, it's a queue to which you can add operations (every operation is Operation-derived class with run method to implement) which are executed either serially, or in parallel or ideally various dependencies can be set on operations (ie that some operation depends on others being executed before it can start).

推荐答案

我也在找.但由于它似乎还不存在,我已经编写了自己的实现:

I'm looking for it, too. But since it doesn't seem to exist yet, I have written my own implementation:

import time
import threading
import queue
import weakref

class OperationQueue:
    def __init__(self):
        self.thread = None
        self.queue = queue.Queue()

    def run(self):
        while self.queue.qsize() > 0:
            msg = self.queue.get()
            print(msg)
            # emulate if it cost time
            time.sleep(2)

    def addOperation(self, string):
        # put to queue first for thread safe.
        self.queue.put(string)
        if not (self.thread and self.thread.is_alive()):
            print('renew a thread')
            self.thread = threading.Thread(target=self.run)
            self.thread.start()





myQueue = OperationQueue()
myQueue.addOperation("test1")
# test if it auto free
item = weakref.ref(myQueue)
time.sleep(1)
myQueue.addOperation("test2")
myQueue = None
time.sleep(3)
print(f'item = {item}')
print("Done.")

这篇关于Python 中是否有来自 ObjectiveC 的 NSOperationQueue 之类的东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆