Tokio::main with worker_threads- what do they share?

I have read in the tokio documentation that you can enable multi threaded-runtimes. The below example is one such program that works, but I am confused about the "counter". It increments with each message received. Shouldn't the first several messages all have a counter = 1 as the messages are sent (via round robin?) to the worker threads? What do they share or not share?

My motivation here is to allow high CPU usage for many messages incoming concurrently, but I wonder if I have the wrong approach.

use std::error::Error;
use tokio_nsq::{NSQChannel, NSQConsumer, NSQConsumerConfig, NSQConsumerConfigSources, NSQConsumerLookupConfig, NSQTopic};

#[tokio::main(flavor = "multi_thread", worker_threads = 10)]
pub async fn main() -> Result<(), Box<dyn Error>> {

    let topic   = NSQTopic::new("names").unwrap();
    let channel = NSQChannel::new("first").unwrap();
    let mut consumer = NSQConsumerConfig::new(topic, channel)
    let mut count: usize = 1; //    WHY AM I "SHARED?"
    loop {
        let message = consumer.consume_filtered().await.unwrap();   
        let message_body_str = std::str::from_utf8(&message.body).unwrap();
        count = count + 1;
        println!("ct={}, message body = {}", count, message_body_str);

The worker_threads option controls how many OS threads the tasks you spawn with tokio::spawn are distributed across. Since you don't spawn any, you only have one task, so only one thread is doing any work.

Consider spawning some tasks with tokio::spawn.

1 Like

Thank you Alice! That is very helpful.