我刚开始使用线程。我知道这个理论并理解它的主要方面,但我在这个主题上只有一点实践。
我正在为以下问题寻找一个好的解决方案(或模式,如果可用)。
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#stop
和Thread#run
。但是,我读到,如果你想要一个稳定的实现,你不应该使用这些方法。并使用某种信号机制。
在ruby中,有一些类一般处理同步和线程协作,如Thread
、Mutex
、Monitor
、 ConditionVariable
等
也许 ConditionVariable
可以成为我的 friend ,因为它允许发出信号,但我不确定。
您将如何实现?
最佳答案
Ruby 提供了一个线程安全的 Queue
类,它会为您处理一些这样的事情:
queue.pop
将阻塞直到一个值被插入队列。以这种方式,您可以让任意数量的线程在队列中等待。如果您推送到队列中的其中一件事是另一个队列或条件变量,那么您可以使用它来表示任务完成。
众所周知,线程很难有效推理。您可能会发现另一种更高级别的方法,例如 celluloid更容易使用。
关于ruby - 你将如何在 ruby 2.0 中实现与信号的保存线程协作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16735229/