Class: ThreadPool::Worker

Inherits:
Object
  • Object
show all
Includes:
Awakenable
Defined in:
lib/threadpool.rb

Instance Method Summary collapse

Methods included from Awakenable

#sleep, #wake_up

Constructor Details

#initialize(pool) ⇒ Worker

Returns a new instance of Worker.



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/threadpool.rb', line 36

def initialize (pool)
	@pool  = pool
	@mutex = Mutex.new

	@thread = Thread.new {
		loop do
			if @block
				begin
					@block.call(*@args)
				rescue Exception => e
					@pool.raise(e)
				end

				@block = nil
				@args  = nil

				@pool.wake_up
			else
				sleep unless die?
				break if die?
			end
		end
	}
end

Instance Method Details

#available?Boolean

Returns:

  • (Boolean)


61
62
63
64
65
# File 'lib/threadpool.rb', line 61

def available?
	@mutex.synchronize {
		!@block
	}
end

#dead?Boolean

Returns:

  • (Boolean)


93
94
95
# File 'lib/threadpool.rb', line 93

def dead?
	@thread.stop?
end

#die?Boolean

Returns:

  • (Boolean)


89
90
91
# File 'lib/threadpool.rb', line 89

def die?
	@die
end

#joinObject



78
79
80
# File 'lib/threadpool.rb', line 78

def join
	@thread.join
end

#killObject



82
83
84
85
86
87
# File 'lib/threadpool.rb', line 82

def kill
	return if die?

	@die = true
	wake_up
end

#process(*args, &block) ⇒ Object



67
68
69
70
71
72
73
74
75
76
# File 'lib/threadpool.rb', line 67

def process (*args, &block)
	return unless available?

	@mutex.synchronize {
		@block = block
		@args  = args

		wake_up
	}
end