erickt / rust-zmq

Rust zeromq bindings.
Apache License 2.0
900 stars 194 forks source link

How to pass a Context between multi-threads? #190

Closed ghost closed 7 years ago

ghost commented 7 years ago

I hope to pass Context as ref, but failed at compiled error[E0382]: capture of moved value: context

--> src/main.rs:29:61 29 children.push(thread::spawn(move worker_routine(&context))); ------- ^^^^^^^ value captured here after move
value moved (into closure) here

= note: move occurs because context has type zmq::Context, which does not implement the Copy trait

error: aborting due to previous error(s)

error: Could not compile mtserver.

  children.push(thread::spawn(move || worker_routine(&context)));

the whole code is below:

extern crate zmq;

use std::{thread, time};

fn worker_routine(context: &zmq::Context) {
    let receiver = context.socket(zmq::REP).unwrap();
    assert!(receiver.connect("inproc://workers").is_ok());

    loop {
        let string = receiver.recv_string(0).unwrap().unwrap();
        println!("Received request: {}", string);
        thread::sleep(time::Duration::from_secs(1));
        receiver.send_str("World", 0).unwrap();
    }
}

fn main() {
    let context = zmq::Context::new();

    let clients = context.socket(zmq::ROUTER).unwrap();
    assert!(clients.bind("tcp://*:5555").is_ok());

    let workers = context.socket(zmq::DEALER).unwrap();
    assert!(workers.bind("inproc://workers").is_ok());

    let mut children = vec![];

    for _ in 0..5 {
        children.push(thread::spawn(move || worker_routine(&context)));
    }

    for child in children {
        let _ = child.join();
    }
}