uazu / qcell

Statically-checked alternatives to RefCell and RwLock
Apache License 2.0
356 stars 22 forks source link

Implement Sync for QCell, LCell and LCellOwner, and Send for TCell. #4

Closed michiel-de-muynck closed 5 years ago

michiel-de-muynck commented 5 years ago

This PR implements Sync and Send for a few types that currently don't implement these traits, but I believe it is safe for these types to implement these traits (with the appropriate bounds on T). The justification for why it's sound is written as comments in the code.

It's not terribly useful for these types to implement these traits, since you almost never use these types in a multithreaded context. However, these cell types are a kind of fundamental building block and it's very hard to imagine all the situations in which they may be used. Perhaps some application could work in phases, building a datastructure full of LCells in a single-threaded phase then reading it concurrently in a multi-threaded phase. Maybe someone wants to put a QCellOwner or LCellOwner into a Mutex or RwLock. It's unlikely, but if it's safe, why not allow it?

Disclaimer: Please don't just click "accept" without convincing yourself that these trait implementations are indeed sound. I believe they are, and I wrote my reasoning in the comments in the code. But I'm not an expert in these things. I could be wrong.

uazu commented 5 years ago

Thanks for the PR. I'll try and figure out the safety reasoning later because I have a cold right now (winter here) and my brain isn't up to it. If we can think of some scenarios where Send or Sync might be required, that would help motivate the change. On the downside it makes doing an unsafe review of the crate harder. An alternative would be to specifically remove the ability to Send for example if that position can also be justified, for example in the name of simplification. I will look at all this when I've cleared this cold.

uazu commented 5 years ago

Thanks. I agree with the reasoning that having everything Send+Sync for QCell makes sense. If multiple threads have & refs to both owner and cell (through Sync), then the only access permitted is ro, so that is fine. If they have & refs to cell, but only one thread has a &mut ref to the owner (possibly through Send) that is also fine because that one thread has rw access, but no other thread has any access. The T: Send+Sync reasoning makes sense too.

I agree that for TCell that it is safe to pass the cells between different owners on different threads via Send. It's a slight change in the understanding of who's owning what, though, so I'll have to document that in my next set of changes. It could have its uses, though, for example moving objects between threads for load balancing.

So I'll merge this change, thanks.

I am going to make some other changes soon -- see the current set of issues. Please add a note if you have any comment on those. In particular I've realized that I've used Cargo features incorrectly, since they must be additive, i.e. adding features must allow more stuff to happen, not less. So I'm planning to split out TCell into two types, e.g. perhaps TCell (for global) and TLTCell (for thread-local). Then the global TCell would have the same behaviour as QCell regarding Send+Sync. This will probably need another minor version upgrade due to breaking the API again.

jrmoulton commented 3 years ago

Is there any documentation on how to implement LCell in a multi-threaded function. I've been trying to replace a mutex with an LCell but because the item and owner and have lifetimes shorter than 'static I can't get it to compile. My current code is:

let handles: Vec<_> = (0..num_threads)
            .map(|thread| {
                let image_clone = Arc::clone(&image);
                thread::spawn(move || {
                    for x in (thread * cols_p_t)..((cols_p_t * thread) + cols_p_t) {
                        for y in 0..HEIGHT {
                            mandelbrot(x, y, &mut owner, &Arc::clone(&image_clone));
                        }
                    }
                })
            })
            .collect();

The error is: cannot infer an appropriate lifetime for lifetime parameter 'id in function call due to conflicting requirements expected &mut LCellOwner<'_> found &mut LCellOwner<'_> but, the lifetime must be valid for the static lifetime...

Is there documentation on a similar situation? Or a workaround?

Would a new issue be a better place to ask this question?

uazu commented 3 years ago

I've enabled the Discussion section now, so that would be a better place to put the question. Your example code doesn't include the LCell stuff. The way LCell works is that you need mutable access to your LCellOwner in the same thread that you're doing your cell borrow. So I think it's not really going to help you in this case. Effectively you'd need a Mutex around the owner.

Also, for this case you could also use a TCell or QCell to start with, which might be easier to debug. The lifetime errors that you get with LCell can be very confusing.

I know there has been a lot of discussion around GhostCell of more complicated techniques. Maybe it's one of those that you're trying to implement? Perhaps if you have a link then it might be easier to understand the idea. Please post in the Discussion section and I'll see if I can help.