ruby - 你将如何在 ruby​​ 2.0 中实现与信号的保存线程协作?

标签 ruby multithreading signals threadpool synchronization

我刚开始使用线程。我知道这个理论并理解它的主要方面,但我在这个主题上只有一点实践。

我正在为以下问题寻找一个好的解决方案(或模式,如果可用)。

Assume there should be a transaction component which holds a pool of threads processing tasks from a queue, which is also part of this transaction component.

Each thread of this pool waits until there's a task to do, pops it from the queue, processes it and then waits for the next turn.

Assume also, there are multiple threads adding tasks to this queue. Then I want these threads to suspend until their tasks are processed.

If a task is processed, the thread, which enqueued the processed task, should be made runnable again.

ruby 类Thread 提供了方法Thread#stopThread#run。但是,我读到,如果你想要一个稳定的实现,你不应该使用这些方法。并使用某种信号机制。

在ruby中,有一些类一般处理同步和线程协作,如ThreadMutexMonitor ConditionVariable

也许 ConditionVariable 可以成为我的 friend ,因为它允许发出信号,但我不确定。

您将如何实现?

最佳答案

Ruby 提供了一个线程安全的 Queue 类,它会为您处理一些这样的事情:

queue.pop

将阻塞直到一个值被插入队列。以这种方式,您可以让任意数量的线程在队列中等待。如果您推送到队列中的其中一件事是另一个队列或条件变量,那么您可以使用它来表示任务完成。

众所周知,线程很难有效推理。您可能会发现另一种更高级别的方法,例如 celluloid更容易使用。

关于ruby - 你将如何在 ruby​​ 2.0 中实现与信号的保存线程协作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16735229/

相关文章:

ruby - Ruby 如何使#initialize 私有(private)化?

ruby-on-rails - 为一个模型设计多个路径

.net - 您能确保所有线程都以特定文化启动吗?

c++ - Qt/C++ 基于比较的信号调度的优雅方式

bash: sleep 过程没有被杀死

python - 基于 Docker 的环境配置中带有 mod_wsgi 的 Apache

ruby-on-rails - 模型关系

ruby-on-rails - Ubuntu - 无法安装 RMagick

c++ - 在 C++11 中,如何不向线程传递参数?

multithreading - 为什么 bool 值需要是原子的?