Hacker News new | ask | show | jobs
by chrisseaton 2685 days ago
What’s the memory model for captured variables being mutated by multiple threads?
2 comments

The same memory model as any other shared variable being mutated by multiple threads - you either explicitly synchronize, or you just don't do it. But given that lambdas are far from the only way to get there - and those other ways are already idiomatic in the language (e.g. statics) - why single out lambdas specifically for this?

The ideal solution is to make this a part of the function type - so that APIs that do intend to invoke lambdas concurrently can mark them as such, and then the language would enforce sharing, while other APIs that do not use lambdas in a concurrent context, can use their full power.

Same thing goes for lambdas that cannot escape vs those that can - if you reflect this in the type system, then you can also support safe nonlocal breaks and returns in the former, for example. One of the early Java lambda proposals, the one by Neal Gafter, did just that, and it was awesome.

> why single out lambdas specifically for this?

Because existing memory models have rules for object fields and rules for publishing objects.

These rules don’t apply to local variables.

They could do - but that’s what I’m asking.

Yea, that seems frightening. I like to think of my local variables as my inaccessible local state. I'd imagine it keeps my JIT happy too. What would it even mean to have a lambda reference to a variable who's stack frame has already popped?
> What would it even mean to have a lambda reference to a variable who's stack frame has already popped?

That bit is simple - the variable is kept alive as long as there is still a lambda that references it.

Don’t think about stacks - that’s an implementation detail and the compiler is free to use a combination of the stack and the heap to implement local variables.

The issue I’m talking about is if one thread writes a local and another reads it, what does that look like?