Skip to content

threads

Counting primes on every processor. thread.map gives each thread a part of the slice, and the closure borrows limit from main; nothing is copied or locked. Derived Show prints the summary.

Terminal window
jihoo run examples/threads.jh
examples/threads.jh
import std.thread
#[derive(Show)]
struct Summary {
blocks: i64
primes: i64
}
fn is_prime(n: i64) -> bool {
if n < 2 {
return false
}
var d = 2
while d * d <= n {
if n % d == 0 {
return false
}
d += 1
}
true
}
fn main() {
let limit = 200000
let size = 10000
var starts = Vec(i64).new()
var s = 0
while s < limit {
starts.push(s)
s += size
}
let counts = thread.map(starts.as_slice(), fn(lo) {
var n = 0
for i in lo..min(lo + size, limit) {
if is_prime(i) {
n += 1
}
}
n
})
var total = 0
for c in counts {
total += c
}
println(Summary { blocks: counts.len(), primes: total })
}

View on GitHub