fizx-thread_pool 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- data/CHANGELOG +2 -0
- data/lib/thread_pool.rb +13 -6
- metadata +1 -1
data/CHANGELOG
CHANGED
data/lib/thread_pool.rb
CHANGED
@@ -1,15 +1,17 @@
|
|
1
1
|
# Hooray
|
2
|
+
require "thread"
|
2
3
|
class ThreadPool
|
3
4
|
class Executor
|
4
5
|
attr_reader :active
|
5
6
|
|
6
|
-
def initialize(queue)
|
7
|
+
def initialize(queue, mutex)
|
7
8
|
@thread = Thread.new do
|
8
9
|
loop do
|
9
|
-
|
10
|
+
mutex.synchronize { @block = queue.shift }
|
11
|
+
if @block
|
10
12
|
@active = true
|
11
|
-
block.call
|
12
|
-
block.complete = true
|
13
|
+
@block.call
|
14
|
+
@block.complete = true
|
13
15
|
else
|
14
16
|
@active = false
|
15
17
|
sleep 0.01
|
@@ -27,20 +29,25 @@ class ThreadPool
|
|
27
29
|
|
28
30
|
# Initialize with number of threads to run
|
29
31
|
def initialize(count, queue_limit = 0)
|
32
|
+
@mutex = Mutex.new
|
30
33
|
@executors = []
|
31
34
|
@queue = []
|
32
35
|
@queue_limit = queue_limit
|
33
36
|
@count = count
|
34
|
-
count.times { @executors << Executor.new(@queue) }
|
37
|
+
count.times { @executors << Executor.new(@queue, @mutex) }
|
35
38
|
end
|
36
39
|
|
37
40
|
# Runs the block at some time in the near future
|
38
41
|
def execute(&block)
|
39
42
|
init_completable(block)
|
43
|
+
|
40
44
|
if @queue_limit > 0
|
41
45
|
sleep 0.01 until @queue.size < @queue_limit
|
42
46
|
end
|
43
|
-
|
47
|
+
|
48
|
+
@mutex.synchronize do
|
49
|
+
@queue << block
|
50
|
+
end
|
44
51
|
end
|
45
52
|
|
46
53
|
# Runs the block at some time in the near future, and blocks until complete
|