Actor模型

Posted feng9exe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Actor模型相关的知识,希望对你有一定的参考价值。

actor是一种面向对象的线程(池)模型,强调对事件的响应;在ios中相当于一种通信简化的runloop模型;

 

对比:数据结构化的线程模型,侧重于强调线程拥有的资源(栈、优先级、状态等);

 

每一个actor背后都有一个线程;

 

解决的问题:

1、内存共享(锁);2、消息接受面向对象化;

 

核心:面向对象的actor在当前线程接收到消息后,将消息的处理调度到处理线程进行处理。

 

Actor模型,又叫参与者模型,其”一切皆参与者(actor)”的理念与面向对象编程的“一切皆是对象”类似,但是面向对象编程中对象的交互通常是顺序执行的(占用的是调用方的时间片,是否并发由调用方决定),而Actor模型中actor的交互是并行执行的(不占用调用方的时间片,是否并发由自己决定)。

在Actor模型中,actor执行体是第一类对象,每个actor都有自己的ID(类比人的身份证),可以被传递。actor的交互通过发送消息来完成,每个actor都有一个通信信箱(mailbox,本质上是FIFO消息队列),用于保存已经收到但尚未被处理的消息。actorA要向actorB发消息,只需持有actorB ID,发送的消息将被立即Push到actorB的消息信箱尾部,然后返回。因此Actor的通信原语是异步的。

http://wudaijun.com/2017/05/go-vs-erlang/

 

 

解决线程的锁的问题

Actor model is an approach to make massive concurrency much easier by eliminating locking and synchronization, which is hard to master and may lead to difficult to detect bugs.

 

func put(_ message:Any, after:Int64) {

        let when = DispatchTime.now() + Double(after * 1000000) / Double(NSEC_PER_SEC)

        

        if let dispatchQueue = self.dispatchQueue {

            dispatchQueue.asyncAfter(deadline: when) {

                self.receive(message)

            }

        } else {

            // FIXME: send error report

            print("self.dispatchQueue is nil")

        }

    }

    

    /**

        No-op function which eats unhandled message.

    */

    open func unhandled(_ message:Any) {

    }

    

    // You shall override this function

    open func receive(_ message:Any) {

        

    }

 

 

Actors in Swift

This is an approach to implement actor model of concurrency in Swift.

What‘s included:

  • simple inbox based on Array
  • serial GCD dispatch queue, created separately for each actor
  • use ! operator to send a message
  • messages can be anything, structs preferred

See SwactorTests.swift for example usage.

 

What are actors?

Actor model is an approach to concurrency known in Erlang, and implemented in Scala. For JVM there is popular framework, Akka

Actor model is an approach to make massive concurrency much easier by eliminating locking and synchronization, which is hard to master and may lead to difficult to detect bugs.

Altough iOS apps are not going to tackle such problems, I found actors as a interesting abstraction over concurrent computation.

 

https://github.com/tomekc/SwiftActors

以上是关于Actor模型的主要内容,如果未能解决你的问题,请参考以下文章

Actor模型和CSP模型的区别

Actor模型

Lite Actor:方舟Actor并发模型的轻量级优化

Actor模型及原理

三分钟掌握Actor和CSP模型

Actor模型