如何用Erlang nif编写单例资源?

rfbsl7qr  于 2022-12-08  发布在  Erlang
关注(0)|答案(1)|浏览(157)

有没有办法用c写一个单例类,然后把它作为资源通过NIF转换成erlang?

m1m5dgzv

m1m5dgzv1#

Resources are just pointers to memory. These pointers could be the direction of an instance of a class (as much of a singleton as you want it to be), thus sharing it with whoever has a copy of the resource or another resource pointing to the same memory.
Keep in mind the following:

  1. Access to the memory should be synchronized, maybe using mutexes or condition variables.
  2. Resources can be sent across nodes, but they are only relevant in the node that created it. If you try to derefernce a resource in another node, you'll get an error.
  3. If a resource is left without references, it may be GC'd like any other term (you're able to provide a destructor). If a resource goes to another node and back, without saving a reference to the resource, it may have been collected.
    Other than that creating the singleton is "as simple" as:
  4. Initialize the memory during NIF module loading, storing it in the module's priv data
  5. Create resources pointing to that memory, use the resources as you want
  6. Access the resource memory through proper synchronization methods

相关问题