【问题标题】:Aren't Python tasklets breaking the rule of no "GOTO"?Python tasklet 不是打破了“没有 GOTO”的规则吗?
【发布时间】:2014-04-03 23:08:03
【问题描述】:

我在 Google 上对 Stackless Python 的 tasklet 进行了大量研究。 每个来源都提到它作为一个线程

stackless.com : Microthreads: tasklets wrap functions allowing them to be launched as microthreads.

disinterest.orgv: Tasklets — Lightweight threads

但是 tasklet 不是并发的。他们逐段执行代码。

这样的代码:

def function(n):
   print n
   print n
   stackless.schedule()

stackless.tasklet(function)(3)
stackless.tasklet(function)(10)
stackless.run()

将打印

3
3
10
10

一个 tasklet 执行一个代码,直到遇到 stackless.schedule() 然后它从开始或从上次暂停的地方执行下一个 tasklet。

每个程序员都知道“无 GOTO”的黄金法则。我的问题是:

这与 GOTO 有何不同?
如果不并行执行,使用 tasklet 有什么好处?
如果它们不是真正的线程,为什么每个消息来源都提到它们作为线程替代品?

【问题讨论】:

    标签: python concurrency python-stackless green-threads


    【解决方案1】:

    和 goto 有什么不同?

    这与 goto 的不同之处在于您没有指定要去哪里。通过产生你的tasklet(调用stackless.schedule()),你所说的只是“我现在完成了;你可以稍后再找我”而不是“从文件x的第n行开始执行”。 “goto 不好”的建议源于这样一个事实,即它允许您编写意大利面条式代码,而您的程序的执行是不可能遵循的。另一方面,Tasklet(或协程)在这方面要好得多,因为您知道每个 tasklet 都会运行到完成。

    如果不是并行执行,使用 tasklet 有什么优势?

    并发不同于并行。并行性是指两个任务实际上同时运行。并发是指两个任务在执行过程中可以重叠,但它们不一定都在完全相同的时刻运行。 Tasklet 是并发的,但不是并行的。 tasklet 的优势基本上是并发性。

    如果它们不是真正的线程,为什么每个消息来源都提到它们作为线程替代品?

    如果您可以放弃并行性,它们是线程的替代品,以获得更低的开销。它们仍然是线程,因为它们仍然允许多个并发执行路径,即使它们不是严格并行的。

    【讨论】:

      【解决方案2】:

      我看不出这与 goto 想象以下内容有何相似之处。

      def Eat():
         while True:
              do_something()
              stackless.schedule()
      def Play():
         while True:
              do_another_thing()
              stackless.schedule()
      
      def Sleep():
          while True:
              do_something_else()
              stackless.schedule()
      
      stackless.tasklet(Eat)()
      stackless.tasklet(Play)()
      stackless.tasklet(Sleep)()
      

      它本质上是单核线程,每个线程都可以决定何时将控制权交给另一个等待的任务

      它与实时操作系统如何实现任务调度非常相似

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-02-15
        • 2011-03-03
        • 1970-01-01
        • 1970-01-01
        • 2014-08-12
        • 1970-01-01
        • 2021-02-17
        相关资源
        最近更新 更多