File: mutex_spec.cr

package info (click to toggle)
crystal 1.6.0%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 18,956 kB
  • sloc: javascript: 1,712; sh: 592; cpp: 541; makefile: 243; ansic: 119; python: 105; xml: 32
file content (46 lines) | stat: -rw-r--r-- 1,041 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
{% skip_file if flag?(:win32) %} # FIXME: enable after #11647

{% if flag?(:musl) %}
  # FIXME: These thread specs occasionally fail on musl/alpine based ci, so
  # they're disabled for now to reduce noise.
  # See https://github.com/crystal-lang/crystal/issues/8738
  pending Thread::Mutex
  {% skip_file %}
{% end %}

require "spec"

describe Thread::Mutex do
  it "synchronizes" do
    a = 0
    mutex = Thread::Mutex.new

    threads = 10.times.map do
      Thread.new do
        mutex.synchronize { a += 1 }
      end
    end.to_a

    threads.each(&.join)
    a.should eq(10)
  end

  it "won't lock recursively" do
    mutex = Thread::Mutex.new
    mutex.try_lock.should be_true
    mutex.try_lock.should be_false
    expect_raises(RuntimeError, "pthread_mutex_lock: ") { mutex.lock }
    mutex.unlock
  end

  it "won't unlock from another thread" do
    mutex = Thread::Mutex.new
    mutex.lock

    expect_raises(RuntimeError, "pthread_mutex_unlock: ") do
      Thread.new { mutex.unlock }.join
    end

    mutex.unlock
  end
end