跨线程共享枚举数 [英] Sharing an enumerator across threads

查看:63
本文介绍了跨线程共享枚举数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从不同的线程调用一个通用的枚举器.当我执行以下操作时,

I want to call a common enumerator from different threads. When I do the following,

enum = (0..1000).to_enum
t1 = Thread.new do
  p enum.next
  sleep(1)
end
t2 = Thread.new do
  p enum.next
  sleep(1)
end
t1.join
t2.join

它会引发错误:

Fiber called across threads.

t1调用一次之后,从t2调用enum时.

when enum is called from t2 after once being called from t1.

  • 为什么Ruby被设计成不允许跨线程调用枚举器(或光纤),并且
  • 是否存在提供类似功能的替代方法?

我猜想枚举器/光纤上的操作的原子性在这里是相关的,但是还不能完全确定.如果那是问题,那么在使用时独占锁定枚举器/光纤将解决此问题,而且我不知道为什么通常禁止跨线程调用枚举器/光纤.如果可以通过使用锁定提供替代方法,那将满足我的需求.

I am guessing that atomicity of an operation on an enumerator/fiber is relevant here, but am not fully sure. If that is the issue, then exclusively-locking the enumerator/fiber while in use shall solve the problem, and I don't know why calling an enumerator/fiber across threads is prohibited in general. If an alternative can be provided by using locking, that would satisfy my need.

推荐答案

您可以使用

You can use Queue

queue = Queue.new
(0..1000).map(&queue.method(:push))

t1 = Thread.new do
  while !queue.empty?
    p queue.pop(true)
    sleep(0.1)
  end
end
t2 = Thread.new do
  while !queue.empty?
    p queue.pop(true)
    sleep(0.1)
  end
end
t1.join
t2.join

这篇关于跨线程共享枚举数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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