2
pub struct FunctionPointers{}

lazy_static! {
    pub static ref FP: FunctionPointers = FunctionPointers{};
}

I am currently experimenting with Vulkan and I need to load the function pointers once after I have created the instance.

I want to write something like this

FP = load_function_pointers(&instance);

And then:

FP.CreateDevice(...);

Which probably needs a lock just to be safe, but after that it can be safely accessed and I don't want to lock it every time I want to call a function.

What are my options?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Maik Klein
  • 15,548
  • 27
  • 101
  • 197
  • There's also the obvious "don't use globals" answer: explicitly pass references to the things that you've loaded. See also [How do I create a global, mutable singleton?](http://stackoverflow.com/q/27791532/155423) which was originally in the context of OpenGL bindings. – Shepmaster Aug 10 '16 at 14:52
  • Also [vulkano](https://github.com/tomaka/vulkano) probably has some ideas about how to manage this state. – Shepmaster Aug 10 '16 at 14:55
  • @Shepmaster I have already looked at vulkano, it stores the instance pointers as an `Arc` in various structs. I assume one would implement deref for `SingletonReader` with Mutex's `get_mut`? – Maik Klein Aug 10 '16 at 15:11
  • `Arc` isn't a synchronization tool, it's just for shared ownership. Accessing an `Arc` should basically be a pointer deref; cloning or dropping it is an atomic variable increment / decrement. I believe that's how I would implement `Deref` though. I probably should try to implement it one of these days ^_^. – Shepmaster Aug 10 '16 at 15:15
  • @Shepmaster But I am not talking about an Arc. I need a global variable that I can mutate, and also access it as if it were immutable. OpenGL is different, the context can't be easily shared, in Vulkan you can call the functions in different threads. I guess I need to create something like a cell that can be mutated with a lock, but also allows access to immutable stuff without needing to lock. – Maik Klein Aug 10 '16 at 16:25
  • What I was actually looking for was an `RWLock` but I think it might actually be better to just use an Arc for the function pointers and explicitly copy them into various structs. – Maik Klein Aug 10 '16 at 16:46
  • Having something that you can lock sometimes and not lock other times doesn't really make sense ;-). You'd always have the potential for a race condition. Instead, construct it once somewhere high up (e.g. `main`) where you can mutate it, then transfer ownership (or share it with `Rc` / Arc`) to the places that need it immutably. – Shepmaster Aug 10 '16 at 16:50

0 Answers0