简体   繁体   English

将Python期货用于没有结果的任务是一个好主意吗?

[英]Is it a good idea to use Python futures for tasks without results?

The question came up, when I started implementing asynchronous set and get operations on an object using the concurrent.futures module like this: 当我开始使用concurrent.futures模块对对象执行异步设置和获取操作时,就会出现问题:

import time
from concurrent.futures import ThreadPoolExecutor

executor = ThreadPoolExecutor(max_workers=2)

class Foo(object):
    def set_something(self):
        def long_running_setter():
            time.sleep(1.5)
            print('Set something')
        return executor.submit(long_running_setter)

    def get_something(self):
        def long_running_getter():
            time.sleep(0.5)
            return 'something'
        return executor.submit(long_running_getter)

foo = Foo()
future = foo.get_something()
print("Got " + future.result())

But now, setting a value and waiting for it becomes a little bit awkward to use and semantically "incorrect" 但是现在,设置值并等待它使用起来有点尴尬,并且语义上“不正确”

foo.set_something().result()

although I feel it's still valid, because the Foo object is at the lowest level and further abstractions could be built on top of the futures. 尽管我认为它仍然有效,因为Foo对象处于最低级别,并且可以在期货之上构建进一步的抽象。

So, to sum up my problem: 因此,总结一下我的问题:

  • Are futures the right kind of abstractions to get/set values asynchronously from an object? 期货是从对象异步获取/设置值的正确抽象吗? Especially for setters which do not return any value? 特别是对于不返回任何值的二传手?
  • Should I add a blocking parameter to set_something in order to get rid of the result() call? 我是否应该在set_something中添加一个blocking参数以摆脱result()调用? I have my doubts with this approach, because then I'd encourage not to use futures at all. 我对这种方法有疑问,因为那样的话我会鼓励不要使用期货。
  • How would you do it? 你会怎么做?

If the action must be completed before you can continue past a certain point in the code, you need some way to block/join/wait. 如果必须先完成操作,然后才能继续执行代码中的特定点,则需要某种方式来阻止/加入/等待。

Python properties are much preferred to Java-style getters and setters (like obj.get_x and obj.set_x ). Python 属性比Java样式的getter和setter(例如obj.get_xobj.set_x )更obj.get_x obj.set_x Because properties masquerade as regular attributes, it'd be bad style to have asynchronous code triggered by a property. 由于属性会伪装成常规属性,因此由属性触发异步代码是不好的样式。

Many people find that object-orientation gets them into trouble with asynchronous code and they prefer to use a more functional style. 许多人发现面向对象使他们陷入异步代码的麻烦,他们更喜欢使用功能更多的样式。 Luckily, Python supports using either programming paradigm. 幸运的是,Python支持使用任何一种编程范例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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