为什么我的简单连接池不执行这些简单的 put 语句? [英] Why won't my simple Connection Pool execute these simple put statements?

查看:48
本文介绍了为什么我的简单连接池不执行这些简单的 put 语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里发布了一个关于如何有效管理线程的问题 如何正确使用线程来连接 ping url?

I posted a question regarding how to effectively manage threads here How do I properly use Threads to connect ping a url?

我得到了一些关于池、线程安全以及一些要使用的库和 gem 的很好的建议和技巧.我正在尝试使用 concurrent-ruby 来创建一个线程/连接池来执行一些线程.在一个简单的 ruby​​ 文件中,我有以下代码:

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

根据 concurrent-ruby 中的文档,我已经完成了所需的步骤,但我的代码无法执行.没有执行 puts 语句.这是另一个例子:

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

此数组的大小为 0.池中的代码未执行.我至少希望尺寸为 1.我已经按照示例设计了 T 恤.为什么这段代码没有执行?

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?

推荐答案

你的代码是正确的,块成功推送到池中.然而,在它被执行之前,程序会终止并杀死池.这就是您看不到任何输出的原因 - 它没有足够的时间来执行作业.

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.

您可以在末尾添加 sleep 语句,或者,为了更优雅的解决方案,告诉池完成所有工作并关闭.这将如下所示:

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

这篇关于为什么我的简单连接池不执行这些简单的 put 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆