简体   繁体   中英

Is there something like NSOperationQueue from ObjectiveC in Python?

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.

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).

have you looked celery as an option? This is what celery website quotes

Celery is an asynchronous task queue/job queue based on distributed message passing. It is focused on real-time operation, but supports scheduling as well.

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.")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM