Why won't my simple Connection Pool execute these simple put statements?

爷,独闯天下 提交于 2021-01-28 09:15:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!