Projects

Ticket #542: testThreadComm.rb

File testThreadComm.rb, 0.7 KB (added by jhemmelg@…, 16 months ago)

Two threads accessing a shared array with mutex protection

Line 
1require 'thread.rb'
2
3class TestLayoutList
4   def initialize
5      @mutex = Mutex.new
6      @ary = Array.new
7   end
8
9   def list
10      @mutex.lock
11      val = @ary.compact
12      @mutex.unlock
13      val
14   end
15
16   def add(item)
17      @mutex.lock
18      @ary.push(item)
19      @mutex.unlock
20   end
21
22   def clear
23      @mutex.lock
24      @ary.clear
25      @mutex.unlock
26   end
27end
28
29layoutList = TestLayoutList.new
30
31t1 = Thread.new {
32   numValues = layoutList.list.length
33   while (numValues < 10000000)
34      p numValues
35      sleep 1
36      numValues = layoutList.list.length
37   end
38}
39
40t2 = Thread.new {
41   (0..10000000).each { |num|
42      layoutList.add(num)
43      #sleep 1
44   }
45}
46
47t2.join
48t1.kill