@@ -13,15 +13,15 @@ module Channel
13
13
describe '#push' do
14
14
it 'should block' do
15
15
t = Thread . new { channel . push 5 }
16
- sleep ( 0.05 )
16
+ t . join ( 0.1 )
17
17
expect ( t . status ) . to eq 'sleep'
18
18
end
19
19
end
20
20
21
21
describe '#pop' do
22
22
it 'should block' do
23
23
t = Thread . new { channel . pop }
24
- sleep ( 0.05 )
24
+ t . join ( 0.1 )
25
25
expect ( t . status ) . to eq 'sleep'
26
26
end
27
27
end
@@ -33,35 +33,42 @@ module Channel
33
33
context 'cooperating threads' do
34
34
35
35
it 'passes the pushed value to thread waiting on pop' do
36
- result = nil
36
+ push_latch = Concurrent ::CountDownLatch . new ( 1 )
37
+ pop_latch = Concurrent ::CountDownLatch . new ( 1 )
37
38
38
- Thread . new { channel . push 42 }
39
- Thread . new { result = channel . pop ; }
39
+ result = nil
40
40
41
- sleep ( 0.1 )
41
+ Thread . new { push_latch . wait ( 1 ) ; channel . push ( 42 ) }
42
+ Thread . new { push_latch . count_down ; result = channel . pop ; pop_latch . count_down }
42
43
44
+ pop_latch . wait ( 1 )
43
45
expect ( result . first ) . to eq 42
44
46
end
45
47
46
48
it 'passes the pushed value to only one thread' do
47
- result = [ ]
49
+ result = Concurrent :: AtomicFixnum . new ( 0 )
48
50
49
- Thread . new { channel . push 37 }
50
- Thread . new { result << channel . pop }
51
- Thread . new { result << channel . pop }
51
+ threads = [
52
+ Thread . new { channel . push 37 } ,
53
+ Thread . new { channel . pop ; result . increment } ,
54
+ Thread . new { channel . pop ; result . increment } ,
55
+ Thread . new { channel . pop ; result . increment }
56
+ ]
52
57
53
- sleep ( 0.1 )
58
+ threads . each { | t | t . join ( 0.1 ) }
54
59
55
- expect ( result . size ) . to eq ( 1 )
60
+ expect ( result . value ) . to eq ( 1 )
56
61
end
57
62
58
63
it 'gets the pushed value when ready' do
59
64
result = nil
60
65
61
- Thread . new { result = channel . pop ; }
62
- Thread . new { channel . push 57 }
66
+ threads = [
67
+ Thread . new { result = channel . pop ; } ,
68
+ Thread . new { channel . push 57 }
69
+ ]
63
70
64
- sleep ( 0.1 )
71
+ threads . each { | t | t . join ( 0.1 ) }
65
72
66
73
expect ( result . first ) . to eq 57
67
74
end
@@ -71,8 +78,7 @@ module Channel
71
78
72
79
it 'does not block' do
73
80
t = Thread . new { channel . select ( probe ) }
74
-
75
- sleep ( 0.05 )
81
+ t . join ( 0.1 )
76
82
77
83
expect ( t . status ) . to eq false
78
84
end
@@ -91,16 +97,14 @@ module Channel
91
97
channel . select ( probe )
92
98
93
99
t = Thread . new { channel . push 72 }
94
-
95
- sleep ( 0.05 )
100
+ t . join ( 0.1 )
96
101
97
102
expect ( t . status ) . to eq 'sleep'
98
103
99
104
new_probe = Channel ::Probe . new
100
105
101
106
channel . select ( new_probe )
102
-
103
- sleep ( 0.05 )
107
+ t . join ( 0.1 )
104
108
105
109
expect ( new_probe . value . first ) . to eq 72
106
110
end
0 commit comments