wboayue / rust-ibapi

An implementation of the Interactive Brokers API for Rust
MIT License
45 stars 21 forks source link

Cannot run concurrent IBAPI as thread safe #97

Closed Pl0414141 closed 1 year ago

Pl0414141 commented 1 year ago

If you try to run two threads to invoke Client::connect in order to connect two clients at the same time will produce an error, see below:

thread 'main' panicked at 'called Result::unwrap() on an Err value: Io(Error { kind: UnexpectedEof, message: "failed to fill whole buffer" })', src/main.rs:40:61 stack backtrace: 0: rust_begin_unwind at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/std/src/panicking.rs:578:5 1: core::panicking::panic_fmt at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/panicking.rs:67:14 2: core::result::unwrap_failed at /rustc/90c541806f23a127002de5b4038be731ba1458ca/library/core/src/result.rs:1687:5 3: ibapi::main note: Some details are omitted, run with RUST_BACKTRACE=full for a verbose backtrace.

wboayue commented 1 year ago

Right now, you can't use a single instance of the client across multiple threads. That's a use case I decided not to handle. This might be a future enhancement. However, multiple threads with their own instance of the client is supported if they use distinct client ids.

Pl0414141 commented 1 year ago

Hi!

Can you provide a minimal code example of "multiple threads with their own instance of the client is supported if they use distinct client ids"?

Thanks a lot!

wboayue commented 1 year ago
    use crossbeam::thread;
    use use ibapi::Client;

    thread::scope(|s| {
        for client_id in 100..103 {
            s.builder()
                .spawn(move |_| {
                    let client = Client::connect("127.0.0.1:4002", client_id)?;
                })
                .unwrap();
        }
    })
    .unwrap();