telegram-bot icon indicating copy to clipboard operation
telegram-bot copied to clipboard

Make telegram_bot_fork::Api safe to send across threads

Open shouya opened this issue 7 years ago • 1 comments

I'm currently working on another small tool that uses futures heavily, then I found it's very difficult to define an Api and use it in the futures. This is because that Api is defined in terms of Rc, which makes it unable to share across threads.

pub struct Api {
    url: Option<String>,
    inner: Rc<ApiInner>,
}

To circumvent this situation, instead of sharing a same Api, I currently pass a String token around and construct the Api on demand. Is there any some obvious solution to this? Or we should probably switch the inner to use Arc instead?

shouya avatar Jan 01 '19 20:01 shouya

Here's a simple example to demonstrate the case:

bot = Api::new("something").unwrap()
let s = futures::stream::unfold((), move |init_n| {
  bot.send(requests::SendMessage::new(ChatId::new(42), "foo"))
    .map(|msg| (msg.id.into(), ()))
});

This piece of code constructs an infinite stream of numbers representing the message ids of the same message sent over and over again. It won't compile since bot is not allowed to be sent across the thread border.

In this particular case, I can simply use the tokio runtime on current_thread to evaluate the stream, but if I need this stream to run in background on another thread, there will be an problem.

shouya avatar Jan 01 '19 21:01 shouya