Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何向函数返回值,然后在同一函数中启动线程?_Ruby_Multithreading - Fatal编程技术网

Ruby 如何向函数返回值,然后在同一函数中启动线程?

Ruby 如何向函数返回值,然后在同一函数中启动线程?,ruby,multithreading,Ruby,Multithreading,有没有一种方法可以向函数返回一个值,然后调用该函数中的线程?例如: def foo return fast_function Thread.new do slow_function end end 这背后的原因是fast\u函数和slow\u函数都写入相同的资源。但是我想确保fast\u函数首先运行并完成,并在slow\u函数写入共享资源之前将其值返回到foo。在某些情况下,slow\u功能在fast\u功能之前完成,我会遇到竞速情况 编辑: 更多关于这个问题的背景。这与我

有没有一种方法可以向函数返回一个值,然后调用该函数中的线程?例如:

def foo
  return fast_function
  Thread.new do
    slow_function
  end
end
这背后的原因是
fast\u函数
slow\u函数
都写入相同的资源。但是我想确保
fast\u函数
首先运行并完成,并在
slow\u函数
写入共享资源之前将其值返回到
foo
。在某些情况下,
slow\u功能
fast\u功能
之前完成,我会遇到竞速情况

编辑:
更多关于这个问题的背景。这与我试图实现的服务器端事件有关。我正在尝试使用
fast\u函数
来计算事件id、返回和html。而
slow\u函数
负责通过事件id通知客户端进程已完成。但是,在某些情况下,
slow\u函数
会在客户端事件知道在何处侦听之前通知客户端,因为
fast\u函数
尚未返回事件id。

否,返回将退出函数,它还将在屈服块中退出函数。在我看来,这个问题有多种解决办法

实际上,它非常适合并发Ruby()

您可以这样使用它:

def foo

   fast = Concurrent::Promise.execute{ fast_function }
   slow = promises[:fast].then{ slow_function }
                         .on_fullfill{ notify_client }
   return fast.value
end
fast = Concurrent::Promise.execute{ fast_function }
slow = Concurrent::Promise.execute{ slow_function }

render fast.value # Or what you ever do with the html. 
                  #.value will wait for the Promise to finish.
result slow = slow.value
正如您所猜测的,它将返回fast函数的值。 但是如果slow函数完成,它也会调用on_fullfill函数(或proc)。最重要的是,它将保证秩序

注意:我不确定我是否理解正确,如果您想同时启动booth线程,但请确保快速线程首先完成。您可以这样做:

def foo

   fast = Concurrent::Promise.execute{ fast_function }
   slow = promises[:fast].then{ slow_function }
                         .on_fullfill{ notify_client }
   return fast.value
end
fast = Concurrent::Promise.execute{ fast_function }
slow = Concurrent::Promise.execute{ slow_function }

render fast.value # Or what you ever do with the html. 
                  #.value will wait for the Promise to finish.
result slow = slow.value
通过这种方式,您可以并行启动booth函数,但请确保您会首先得到快速函数的答案


编辑1:我考虑过这个问题,我不确定您是否想要一个异步任务。这很难说,因为你贴了一个最小的例子(什么是正确的coruse)。 如果您只想让一个函数以正确的顺序返回两个函数,您可以执行以下操作:

def foo
  yield fast_function
  yield slow_function
end

听起来您希望同步代码而不是异步代码。您不希望跨线程拥有可变数据,这是一种主要的代码气味。