antoyo / relm

Idiomatic, GTK+-based, GUI library, inspired by Elm, written in Rust
MIT License
2.44k stars 78 forks source link

Should we combine the `Channel` and the `Sender` types? #311

Open marmistrz opened 1 year ago

marmistrz commented 1 year ago

When writing multithreaded core, using channels is quite messy. For each channel, you need to store both the channel (which you will never touch afterwards) and the sender (which is the one you use). In real-life examples, where CPU-intensive operation are triggered by the interactions with the UI, both need to be stored in the model. This feels quite messy.

Is there any reason against combining these two types into a single one?

antoyo commented 1 year ago

It's been a while since I wrote this, but I believe the Channel type cannot be sent to another thread. Have you tried to do so?

marmistrz commented 1 year ago

glib::Source implements Send and so does relm::Channel. I checked it by adding a drop(channel) to the end of the spawned closure in multithread.rs and the example works perfectly well.

antoyo commented 1 year ago

Wouldn't that create a race condition where it could be possible that the channel is dropped before the other thread received the message?

The Channel is like a Receiver, so it is usual to have 2 halves when creating a channel. It's just that the one in relm doesn't have a recv() method and looks unused as a result.

marmistrz commented 1 year ago

Perhaps, I think about the following sequence:

  1. Sender sends
  2. Sender is dropped
  3. Channel is dropped
  4. Receiver tries to receive.

Would it make sense to possibly allow storing the channel within the relm context, given that in most usecases this will be the lifetime of the channel and that the channel is tied to the relm stream? fwiw, I think about Box::leaking the channel in my case so that I don't have to store a _channel per channel

antoyo commented 1 year ago

Would it make sense to possibly allow storing the channel within the relm context, given that in most usecases this will be the lifetime of the channel and that the channel is tied to the relm stream?

I'm not sure I understand what you suggest. Could you please provide a code example and what it would generate?