如何并发执行功能

时间:2019-05-08 13:22:37

标签: elixir

我是FP和elixir的新手,我试图同时执行以下功能。但这卡在read()上。我尝试了Task.asyncspawn_link并在其中传递函数,但是没有用

defmodule MyFile do


def start() do

read()
write()


#Task.async(read())
#Task.async(write())
end



def read() do
case 1 do
  1 -> IO.puts "this  is one"
  2 -> IO.puts "this is two"
  _ -> IO.puts "this is dont care "
end
   read()
end


def write() do

case 1 do
  1 -> IO.puts "THIS IS ONE OF WRITE"
  2 -> IO.puts "THIS IS TWO OF WRITE"
  _ -> IO.puts "this is dont care "
end
   write()
end


end

它正在控制台上打印"this is one",因此write()中的start()函数永远不会执行,因为控件位于read()内部。在这种情况下,我该如何启动两者并同时执行?

2 个答案:

答案 0 :(得分:1)

您应该使用其他进程来启动readwrite函数。之后,他们将msg发送回如下所示的主进程以同时打印它。下面的代码可以帮助您了解更多。

defmodule Doan do

def start() do
  current = self()
  spawn(Doan, :read, [current])
  spawn(Doan, :write, [current])
  loop()
end

def loop do
  receive do
    {:read, 1} -> IO.puts "this  is one"
    {:write, 1} -> IO.puts "THIS IS ONE OF WRITE"
    {:read, 2} -> IO.puts "this is two"
    {:write, 2} -> IO.puts "THIS IS TWO OF WRITE"
    _ -> IO.puts "this is dont care "
  end
  loop()
end

def read(pid) do
  send pid, {:read, 1}
  :timer.sleep(500)
  read(pid)
end

def write(pid) do
  send pid, {:write, 1}
  :timer.sleep(500)
  write(pid)
end
end

并在shell上显示结果

enter image description here

答案 1 :(得分:1)

您和Task.async/1差不多了。唯一的事情是您需要提供一个[匿名]函数作为其参数,而您又调用了该函数。

defmodule RW do
  def start() do
    #          ⇓⇓⇓⇓⇓⇓⇓ HERE
    Task.async(&read/0) # or fn -> read() end
    Task.async(&write/0)
    :ok
  end

  def read(counter \\ 10) do
    IO.puts "this is one"
    unless counter <= 0, do: read(counter - 1)
  end

  def write(counter \\ 10) do
    IO.puts "THIS IS ONE OF WRITE"
    unless counter <= 0, do: write(counter - 1)
  end
end

产生的结果(我明确终止是在执行10次之后):

iex> RW.start
# this is one
# THIS IS ONE OF WRITE
# this is one
:ok
# THIS IS ONE OF WRITE
# this is one
# THIS IS ONE OF WRITE
# this is one
# THIS IS ONE OF WRITE
# THIS IS ONE OF WRITE
# this is one
# THIS IS ONE OF WRITE
# this is one
# THIS IS ONE OF WRITE
# this is one
# THIS IS ONE OF WRITE
# this is one
# THIS IS ONE OF WRITE
# this is one
# THIS IS ONE OF WRITE
# this is one
# THIS IS ONE OF WRITE
# this is one

请注意,RW.start/0:ok的2个输出和read/1的1个输出之后以write/1退出。您无需控制流程即可执行任务。