@@ -13,15 +13,15 @@ module Channel
1313 describe '#push' do
1414 it 'should block' do
1515 t = Thread . new { channel . push 5 }
16- sleep ( 0.05 )
16+ t . join ( 0.1 )
1717 expect ( t . status ) . to eq 'sleep'
1818 end
1919 end
2020
2121 describe '#pop' do
2222 it 'should block' do
2323 t = Thread . new { channel . pop }
24- sleep ( 0.05 )
24+ t . join ( 0.1 )
2525 expect ( t . status ) . to eq 'sleep'
2626 end
2727 end
@@ -33,35 +33,42 @@ module Channel
3333 context 'cooperating threads' do
3434
3535 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 )
3738
38- Thread . new { channel . push 42 }
39- Thread . new { result = channel . pop ; }
39+ result = nil
4040
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 }
4243
44+ pop_latch . wait ( 1 )
4345 expect ( result . first ) . to eq 42
4446 end
4547
4648 it 'passes the pushed value to only one thread' do
47- result = [ ]
49+ result = Concurrent :: AtomicFixnum . new ( 0 )
4850
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+ ]
5257
53- sleep ( 0.1 )
58+ threads . each { | t | t . join ( 0.1 ) }
5459
55- expect ( result . size ) . to eq ( 1 )
60+ expect ( result . value ) . to eq ( 1 )
5661 end
5762
5863 it 'gets the pushed value when ready' do
5964 result = nil
6065
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+ ]
6370
64- sleep ( 0.1 )
71+ threads . each { | t | t . join ( 0.1 ) }
6572
6673 expect ( result . first ) . to eq 57
6774 end
@@ -71,8 +78,7 @@ module Channel
7178
7279 it 'does not block' do
7380 t = Thread . new { channel . select ( probe ) }
74-
75- sleep ( 0.05 )
81+ t . join ( 0.1 )
7682
7783 expect ( t . status ) . to eq false
7884 end
@@ -91,16 +97,14 @@ module Channel
9197 channel . select ( probe )
9298
9399 t = Thread . new { channel . push 72 }
94-
95- sleep ( 0.05 )
100+ t . join ( 0.1 )
96101
97102 expect ( t . status ) . to eq 'sleep'
98103
99104 new_probe = Channel ::Probe . new
100105
101106 channel . select ( new_probe )
102-
103- sleep ( 0.05 )
107+ t . join ( 0.1 )
104108
105109 expect ( new_probe . value . first ) . to eq 72
106110 end
0 commit comments