Skip to content

Frequent use of std::sync::Mutex in ipstack causes performance issues #62

Open

Description

@SajjadPourali

In the ipstack, we frequently use std::sync::Mutex, which can lead to performance degradation due to thread blocking. Ideally, we should replace these with non-blocking synchronization mechanisms to prevent thread contention and improve performance.

Activity

  1. changed the title [-]Frequent use of std::sync::Mutex in ipstack causes performance issues[/-] [+]Frequent use of `std::sync::Mutex` in ipstack causes performance issues[/+] on May 7, 2025
  2. ssrlive commented on May 8, 2025

    @ssrlive
    Collaborator

    There is currently no known approach to use a tokio::sync:Mutex in both tcp_main_logic_loop and poll_read at the same time.

    But I don't think the performance bottleneck is here.

  3. SajjadPourali commented on May 8, 2025

    @SajjadPourali
    CollaboratorAuthor

    There is currently no known approach to use a tokio::sync:Mutex in both tcp_main_logic_loop and poll_read at the same time.

    There are some tricks including the following approach, however its implementation in our code is not straightforward.

    struct Test {
        d: Arc<Mutex<u8>>,
        b: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
    }
    
    async fn change_value(m: Arc<Mutex<u8>>) {
        let mut guard = m.lock().await;
        *guard = 1;
    }
    
    impl AsyncRead for Test {
        fn poll_read(
            mut self: Pin<&mut Self>,
            ctx: &mut Context<'_>,
            _: &mut ReadBuf<'_>,
        ) -> Poll<Result<(), std::io::Error>> {
            let mut fut = self
                .b
                .take()
                .unwrap_or(Box::pin(change_value(self.d.clone())));
            match fut.as_mut().poll(ctx) {
                Poll::Pending => {
                    self.b = Some(fut);
                    Poll::Pending
                }
                Poll::Ready(_) => Poll::Ready(Ok(())),
            }
        }
    }

    But I don't think the performance bottleneck is here.

    I’m not sure about its impact on performance; we can also run a profiler like pprof-rs to evaluate it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions