In my previous article on Crystal Programming Language titled — “A First Look at Crystal Programming Language and its Ecosystem_”, _I wrote about my first experience with Crystal language and its ecosystem. Since then I tried to delve a bit more in Crystal’s syntax and semantics. Having already familiar with Go, I wanted to compare concurrency support in Crystal and Go by converting some Go programs into Crystal.

I make the assumption that you are familiar with at least one of these two languages and its concurrency constructs.

Go supports two forms of concurrency and both are very mature —

Image for post

While Crystal also supports CSP and Shared Memory Multithreading, I found the later support still incomplete as of Crystal version 0.35.1. Also, as Crystal official documentation says — “At the moment of this writing, Crystal has concurrency support but not parallelism: several tasks can be executed, and a bit of time will be spent on each of these, but two code paths are never executed at the same exact time.”

Having said that I will compare the current state of Crystal’s concurrency with Go’s by comparing support for CSP in this part I of article series. I will follow up with a part II comparing Shared Memory Multithreading.

Communicating Sequential Processes (CSP)

In CSP, values are confined within single activity and multiple activities communicate by passing values among them.

Go implements CSP using —

  • goroutine — lightweight thread of execution
  • channel — communication mechanism that lets one goroutine send values to another goroutine.

Crystal has similar mechanism using —

  • fiber — equivalent to goroutine in Go
  • channel — equivalent to channel in Go

For this article, I took the examples from A Tour of Go (Concurrency section) and converted the programs to Crystal equivalent.

Let’s go over the programs one by one now.

Concurrency 1

This example shows how to create goroutine (Go) / fiber (Crystal) and execute them concurrently.

Go version — https://tour.golang.org/concurrency/1

Here —

  • line 16go keyword creates a new goroutine in Go
  • line 8–13: main goroutine and newly created goroutine (line 16) runs concurrently and executes **say **function

Crystal version —

#golang #ruby #ruby-on-rails #crystal-lang #go

Comparing Crystal’s concurrency with that of Go (Part I)
4.65 GEEK