Is it okay to use infinite loop in an async function?

I formatted the code above and Depending on the message type I want to either set some key in redis or delete from redis and insert into postgres I use bb8 for those so they are async functions. The reason I cannot use async verion of read_message is because it does not exists. Redis library does not expose any way of handling pubsub through an async interface.

if they are not in an Arc<Mutex<>> How will I be sharing them among threads safely ?

You should not be sharing channels among threads, except by cloning the channel handles directly. Are you sure you should be using async for this at all?

the entire redis and postgres library is async since I also use that in actix handlers. I dont really want to write sync versions of 20+ methods. Again the only problem is the calls to read_message which requires a special redis pubsub client which synchronously waits for the messages so this is due to the conflicts in the design of the redis crate

Ah, so setting or deleting keys in Redis doesn't require blocking?

No they dont and I already implemented them in my store api in a nice async way

so the only thing that will be blocking in the entire service is the call to read_message and I will be awaiting other things right under that call

Cool. This should work pretty well then:

use tokio::sync::mpsc::unbounded_channel;

let (tx, rx) = unbounded_channel();

std::thread::spawn(move || {
    loop {
        let details = redis.get_message(...).unwrap();
        tx.send(details).unwrap();
    }
});

// This loop will run every time the redis pubsub service gets a message.
while let Some(details) = rx.recv().await {
    // handle details
}
// If the loop gets here, then the thread we spawned has panicked.

EDIT: With the latest version of Tokio, you can also use a bounded channel, as Tokio's bounded channel has been given a blocking_send method.

5 Likes

the thread here is an os thread right ?

Yes.

thanks this was the thing I was looking for.

1 Like

Glad I could help! :+1:

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.