Reading two lock iterators

I use the Rust websocket library to talk with things, and I have this thread that looks something like this:

thread::spawn(move || { while let Ok(Message::Text(text)) = receiver.recv_message() { /* Do some stuff */ } }); 

The above receiver may also be a blocking iterator:

 thread::spawn(move || { for message in receiver.incoming_messages() { /* Do same stuff */ } }); 

I want to send a signal to this thread so that it stops doing something. I thought mpsc::channel would be great for sending this signal. select! It looked like a way, but it only works if all channels are of type mpsc::channel .

Is there something that can join the two lock iterators and provide a result as data arrives? Or any other solution to this problem? I would like to avoid creating a stream for each input source and managing my own queue.

+5
source share
1 answer

Is there something that can join the two lock iterators and provide a result as data arrives? Or any other solution to this problem?

Although I certainly hope that someone will prove to me that I am wrong, I think that the answer should be no. By definition, something that blocks it will prevent further work on this thread. You need something that can distinguish between the states of "done", "read nothing" and "read something", and which cannot be built on top of building blocks that give only two of these states.

I would like to avoid creating a stream for each input source and managing my own queue.

I see no way around this. Since a blocking iterator blocks a stream, having multiple threads allows you to add a "read nothing" state.

The best solution would be to have both input sources have all 3 states.

 loop { if let Ok(Message::Text(text)) = receiver.recv_message() { // Do some stuff } else if let Err(TryRecvError::Disconnected) = kill.try_recv() { break; } else { // Something intelligent for the other cases? } } 
+1
source

All Articles