什么时候为 Scala 演员的反应创建线程? [英] When are threads created for Scala actor's reacts?

查看:42
本文介绍了什么时候为 Scala 演员的反应创建线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在阅读了在 Scala 的 actor 中使用 react 之后,我认为 react 会共享同一个线程,因为没有多个 react> 待定.好像不是这样.

After reading about using react in actors in Scala, I thought react's would share the same thread given there weren't multiple react's pending. It doesn't seem to be the case.

import scala.actors.Actor
import scala.actors.Actor._

class SleepyReactor extends Actor {
    def act() {
        loop {
            react {
                case x => {
                    println("reacting to %s on thread %s".format(x, Thread.currentThread.getName))
                    Thread.sleep(1000)
                    println("done with " + x)
                }
            }
        }
    }
}
val sleepyOne = new SleepyReactor
sleepyOne.start
sleepyOne ! "first" // runs on thread-5

// wait until completion

sleepyOne ! "second" // runs on thread-3

有人可以解释为什么这些 react 运行在不同的线程上,以及何时为具有 react 的 actor 创建新线程?

Can someone explain why these react's are running on different threads and when a new thread is created for an actor with react?

我在某处读到 react 是基于事件的,我认为这意味着反应演员"共享一个线程,如果一个反应演员"正在反应",其他反应演员"将排队,直到首先完成了.我现在觉得我错了.这是如何工作的,它与接收有何不同?

I read somewhere react is event based, and I took that to mean that "react actors" shared a thread and if one was "reacting" the other "react actors" would be queued until the first was done. I now think I am wrong. How does this work, and how is it different than receive?

推荐答案

对于纯基于事件的actor来说,它的反应代码与消息发送代码运行在同一线程上.

It is true that for a pure event-based actor, its reacting code runs on the same thread as message sending code.

但是在 Scala 中,由于当 Actor 在其 React 代码中调用阻塞操作时阻塞线程并统一基于事件和基于线程的 Actor(能够组合它们)是不可取的,因此两种类型的 Actor 都使用相同的线程池,但基于线程的参与者获得自己的线程,而基于事件的参与者基于任务队列共享线程.有关详细信息,请参阅 Philipp Haller 和 统一线程和事件的演员和马丁·奥德斯基

But in Scala, since it's not desirable to block a thread when an actor calls a blocking operation inside its react code and to unify event-based and thread-based actors(being able to compose them), both type of actors uses the same thread pool but the thread-based actors get their own threads whereas event-based actors shares threads based on a task queue. For details, please see Actors that Unify Threads and Events by Philipp Haller and Martin Odersky

这篇关于什么时候为 Scala 演员的反应创建线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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