metal-rs icon indicating copy to clipboard operation
metal-rs copied to clipboard

Integrate auto-release pool into the type system

Open kvark opened this issue 5 years ago • 4 comments

I find it rather obscure that we have no control over when something is released if it decides to use an auto-release pool. I wonder if we could encode this into the type system, so that a user-provided auto-release context is required in any operation that ends up using it implicitly. Something along these lines:

impl Foo {
    fn some_operation(&self, arc: &AutoReleaseContext) {..}
}

fn main() {
    autoreleasepool(|context| {
      foo.some_operation(context);
    })
}

is this feasible or totally unrealistic? @grovesNL @scoopr @SSheldon

kvark avatar Jun 14 '19 23:06 kvark

In principle, just about any obj-c code should be assumed to require autoreleasepool. Empirical proof that a method doesn't need it is not fully sound, as a system update might always change the underlying libs to change the fact. So are you suggesting all objc calling code would have something in the type that ensures a pool exists?

scoopr avatar Jun 17 '19 19:06 scoopr

I find it rather obscure that we have no control over when something is released if it decides to use an auto-release pool.

@kvark I believe that ObjC code that relies on an autorelease pool running or not running until specific times would generally be considered unsound. If something is autoreleased and returned to you, you must retain it if you care about it staying alive.

In your example, some_operation knows that an autorelease pool will not be drained in the middle of it, and that should be enough for it. If it wants to take some object and keep it around for longer, it should retain that object. If it wants to return an object, it can autorelease it and it is the caller's responsibility to retain the object.

Are there any specific situations where you're worried about objects being autoreleased too early? I'd recommend retaining them and using some smart pointer types that don't release until dropped.

SSheldon avatar Jun 18 '19 05:06 SSheldon

I find auto-release pools managed by the system to be unreliable. IIRC, we clearly see a memory leak if we don't wrap execution of relevant bits with ar-pool. Maybe it's a winit issue? We've been trying to cover all the essential code bits in our own pools, so that we can guarantee the memory is freed, that's why I thought about this idea...

kvark avatar Jun 18 '19 05:06 kvark

Aha! My bad. So you're just interested in guaranteeing that this code is run inside some autorelease pool, not necessarily that the pool lasts for a certain duration?

That's not a problem I've thought about very much. In iOS or mac apps, the first thing main usually does is set up an autorelease pool, and then parts of the runtime will create more from there.

Is there any option like that here? Maybe it could be done in winit?

SSheldon avatar Jun 18 '19 06:06 SSheldon