问题
I posted a question regarding how to effectively manage threads here How do I properly use Threads to connect ping a url?
I got some great recommendations and tips regarding pools, thread safety, and some libraries and gems to use. I'm trying to execute one of the recommendations listed by using concurrent-ruby to create a thread/connction pool to execute some threads. In a simple ruby file I have the following code:
pool = Concurrent::FixedThreadPool.new(5)
pool.post do
puts 'hello'
end
As per the documentation in concurrent-ruby I've done the required steps but my code won't execute. No puts statement is being executed. Here is another example:
pool = Concurrent::FixedThreadPool.new(5)
array = []
pool.post do
array << 1
puts 'Why am I not working?'
end
puts array.size
The size of this array is 0. the code in the pool is not executing. I would have at least expected a size of 1. I've followed the example to a tee. Why is this code not executing?
回答1:
Your code is correct and the block is successfully pushed to the pool. However, before it gets executed, the program terminates and kills the pool. That's why you don't see any output - it did not have enough time to execute the job.
You can either add sleep
statement at the end or, for more elegant solution, tell the pool to finish all the work and shut down. This will look like this:
require 'concurrent-ruby'
pool = Concurrent::FixedThreadPool.new(5)
pool.post do
puts 'hello'
end
pool.shutdown
pool.wait_for_termination
来源:https://stackoverflow.com/questions/60175650/why-wont-my-simple-connection-pool-execute-these-simple-put-statements