0

Suppose you have a web server that receives requests via an async closure, like in hyper or warp. You want requests to modify a shared datastructure—e.g. a running count of all requests so far, or a list of the first byte of each request.

How do you do this?

Attempted outline (doesn't work):

#[tokio::main]
async fn main() {
    let mut y = SharedDatastructure::new();
    let hello = warp::path!("hello" / String)
        .map(|name| {
            // first, do some processing
            let data = name + "!"; 
            // then access a shared datastructure
            y.update(data);
            y.get_next_response()
        });

    warp::serve(hello)
        .run(([127, 0, 0, 1], 8000))
        .await;
}

The problem is that you can't update the SharedDatastructure in multiple threads. I tried to pass an broadcast, but you need to create a new producer for every request, and I can't do that either outside the closure—when you don't know how many producers there will be—or inside it.

Herohtar
  • 5,347
  • 4
  • 31
  • 41
Test
  • 962
  • 9
  • 26
  • 1
    Does this answer your question [How can I achieve shared application state with Warp?](/q/66111599/2189130) Using `Arc>` is commonplace. – kmdreko Sep 24 '22 at 20:16
  • 1. Why is it std::sync::Mutex and not tokio::sync::Mutex? 2. Is this the best solution for very high-performance applications? I noticed the mini redis example doesn't use Arc>. They loop { ... } – Test Sep 24 '22 at 20:38
  • Suggesting a different synchronization method for performance would rely on the data you need to share: Is it simple counters? consider using an atomic. Is is map-like? consider using a concurrent collection like dashmap. If your updates are diverse yet small and not-contentious, `std::sync::Mutex` will work just fine. If your updates are diverse and long or contentious, using an async mutex would suit you better. And above all, test! What gives the best performance relies on your specific details. – kmdreko Sep 24 '22 at 20:47
  • The most common operation is adding an entry to a btree. That is usually it. What is "contentious"? – Test Sep 24 '22 at 20:52
  • 1
    Contentious means there's multiple things *contending* to acquire the lock. Look up "lock contention" for more resources. – kmdreko Sep 24 '22 at 21:59

0 Answers0