1

Consider this example -

class Test
   @@store = ""
end

Here store is a class variable of Test and can be mutated from anywhere.

Suppose i am runing my program in multi thread mode & so variable store can be mutated from multiple thread at a time.

My question is - will deadlock arise or crystal-lang handles it in some way due to fiber scheduling ?

If deadlock arises what is the recommended way to solve above program. If you can provide a code from this problem, that would be better.

Ujjwal Kumar Gupta
  • 2,308
  • 1
  • 21
  • 32

1 Answers1

3

No, a deadlock would not arise since Crystal does no implicit locking around variable access. But it's very easy to write thread unsafe code with global state like this.

BAD EXAMPLE:

module Test
  @@store = "a"

  def self.run
    spawn do
      @@store = @@store == "a" ? "b" : "c"
    end

    @@store = @@store == "b" ? "d" : "e"
  end
end

Test.run

When running this program with multithreading @@store might either be "b", "c", "d" or "e" at the end of the program (in practice you'll see all but one result very rarely because there's not a lot going on and not a lot of contention, so it will be quite stable within an execution environment).

Crystal provides some synchronization primitives such as Mutex and Atomic, but the general recommendation is to prefer passing immutable data over Channels rather than mutable data sharing between fibers.

Jonne Haß
  • 4,792
  • 18
  • 30