as

Projects / rust-concurrent-threads

rust-concurrent-threads

Std-only Rust threads. One example per idea, then a prime count on every core.

Why

I was learning the concurrency the language ships: spawn and join, channels, Arc<Mutex>, scoped threads, atomics. A crate would hide the part I was trying to see. The last program counts primes on every core and prints the speedup over one thread, so the examples end in a number you can check.

Diagrams

A solid outline is the path in the repo. A dashed outline is the alternative that shape is refusing.

Each file is one idea: spawn and join, channels, Arc<Mutex>, scoped threads, atomics. cargo run --example runs that idea. cargo run --release counts primes on every core and prints the speedup.

flowchart TD
  ex["cargo run --example"]
  ideas["spawn, channels, Arc, scoped threads, atomics"]
  bench["release build, prime count"]
  ex --> ideas --> bench
  class ex,ideas,bench chosen
          

The question is cores and the primitives in std. An async runtime answers a different question. A crate would hide the part the examples are there to show. Sharing is a channel, an Arc, or a scoped thread.

flowchart TD
  q{Which concurrency}
  q -->|"spawn, join, and the primitives in std"| threads["Std threads"]
  q -->|"tasks on a runtime"| async["Async"]
  q -->|"a crate in front of the primitive"| crate["An external runtime"]
  class threads chosen
  class async,crate rejected
          

Why this shape

Each file is one idea, and cargo run --example runs that idea. The benchmark is cargo run --release. No async runtime. The question is threads and cores, and async would answer a different question. Sharing is explicit: a channel, or an Arc, or a scoped thread. Nothing global.

Where it breaks

The speedup is for this prime loop on this machine. A laptop with a busy fan will not match a quiet one. The examples also do not cover what happens when the mutex is the bottleneck. That would be a different program, and it would look slower with more threads.