Closure may outlive the current function Error

Hi everybody
I hope you're having a great weekend
I have a few problems with the following code, and they are all ownership problems.
The day I learn how to fix my ownership problems, is the day I can walk in the rust kingdom freely.

I removed unrelated lines

fn main() {
    let listener = TcpListener::bind(format!("{}", port)).unwrap();
    let q = ArrayQueue::<TcpStream>::new(1000);

    let conn_collector = thread::spawn(|| {
                                       // ^^ may outlive borrowed value `q`
        for stream in listener.incoming() {
            match stream {
                Ok(stream) => {
                    q.push(stream); // <-== `q` is borrowed here

    while some_condition{
        match q.pop() {
            Ok(stream) => {
                thread::spawn(move || {

First thread::spawn has a closure which needs to have access to q and listener, but I also need those variables outside the closure in order to pop() from q and later drop the listener.
I understand the errors, but I don't know how to solve them,

Although ArrayQueue can be accessed concurrently from several threads, you still need to use some other method of sharing it between those threads. You probably want an Arc for this.

1 Like

Thanks for introducing Arc to me @alice, It is a pretty powerful tool for solving ownership issues.

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