R2d2_postgres number of threads

Anyone know where the range in the code below, I assume the "for _ 0..10i32" is the number of threads to generate, but here does the range, (number of threads) get derived from?

for i in 0..10i32 {
        let pool = pool.clone();
        thread::spawn(move || {
            let mut client = pool.get().unwrap();
            client.execute("INSERT INTO foo (bar) VALUES ($1)", &[&i]).unwrap();
        });
    }

For CPU-bound tasks you can use the num_cpus crate to get the number of cores the CPU has, which is usually the right number of threads to use.

For a database, that's trickier and depends on the database. You may be limited to one query at a time per connection anyway, and may not benefit from multiple threads. If you use a new connection per thread, then it depends on how many connections the db accepts.

Alternatively, you can use rayon to spawn tasks on its own thread pool. Then you don't manage your threads directly, and just run any code you want via rayon, and it will manage the threads for you.

Thanks! That explains it well.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.