$0.02273 -3.06%
SNT · 33w

Nim vs Crystal - Part 2 - Threading & Tooling

Welcome back to my series comparing the two sweethearts of the modern low-level programming world. In part 1, I talked about my views on the interoperability of the two languages, alongside the performance figures of both. Article #1 managed to throw-up a couple of surprises, but I have to admit; these made it all the more enjoyable to write!

In this article, we’re going to look into the commodity that would have changed the aforementioned performance figures, namely concurrency & parallelism, and then into the things that attract me most to programming languages; which is he in-built tooling available. As I know it’ll be useful; I won’t cover only the in-built tooling, but I’ll include my favourite external package too.

Threading Nim Parallelism Primitives

Nim has two flavours of parallelism:

Structured parallelism via the parallel statement. Unstructured parallelism via the standalone spawn statement.

Nim has a builtin thread pool that can be used for CPU intensive tasks. For IO intensive tasks the async and await features should be used instead. Both parallel and spawn need the threadpool module to work.

import threadpoolproc processLine(line: string) = discard "do some heavy lifting here"for x in lines("myinput.txt"): spawn processLine(x)sync()

The parallel statement is the preferred way to use parallelism in a Nim program.

import strutils, math, threadpool{.experimental: "parallel".}proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1)proc pi(n: int): float = var ch = newSeq[float](n+1) parallel: for k in ch[k] = spawn term(float(k)) for k in result += ch[k]echo formatFloat(pi(5000))

Threading support in Nim is part of the system module. To activate thread support you need to compile with the --threads:on command line switch.

Nim’s memory model for threads is quite different from older common programming languages (C, Pascal), but similar to Gola...

Continue on
Recent news
No posts found