通过推送通知醒来 [英] Waking up by push notification

查看:63
本文介绍了通过推送通知醒来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设:

  • 有一些对象(例如数组a)和依赖于该对象的条件(例如a.empty?).
  • 当前线程以外的某些线程可以操纵对象(a),因此条件的评估值的真实性会随时间变化.
  • There is some object (e.g., an array a) and a condition dependent on the object (e.g., such as a.empty?).
  • Some threads other than the current thread can manipulate the object (a), so the truthness of the evaluated value of the condition changes over the time.

当条件满足时,如何让当前线程在代码中的某个位置休眠并通过推送通知继续(唤醒)?

How can I let the current thread sleep at some point in the code and continue (wake up) by push notification when the condition is satisfied?

我不想这样轮询:

...
sleep 1 until a.empty?
...

也许使用Fiber是一个线索.

推荐答案

也许我不太了解您的问题,但是我想ConditionVariable是解决此类问题的好方法.

Maybe I do not quite understand your question, but I guess ConditionVariable is a good approach for such problem.

因此,ConditionVariable可用于在发生某些情况时向线程发出信号.让我们看看:

So, ConditionVariable can be used to signal threads when something happens. Let's see:

require 'thread'

a = [] # array a is empty now
mutex = Mutex.new
condvar = ConditionVariable.new 

Thread.new do
  mutex.synchronize do
    sleep(5)
    a << "Hey hey!"
    # Now we have value in array; it's time to signal about it
    condvar.signal
  end
end

mutex.synchronize do
  condvar.wait(mutex)
  # This happens only after 5 seconds, when condvar recieves signal
  puts "Hey. Array a is not empty now!"
end

这篇关于通过推送通知醒来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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