codecamp

Elixir send和receive

我们可以用send/2发送信息给进程,并用receiver/1接收:
iex> send self(), {:hello, "world"}
{:hello, "world"}
iex> receive do
...>   {:hello, msg} -> msg
...>   {:world, msg} -> "won't match"
...> end
"world"

当一个信息传送至进程,它被存放在进程的邮箱中.receive/1块会进入当前进程的邮箱,搜索是否有能模式匹配成功的信息.receive/1支持卫语句和多从句,例如case/2.

如果邮箱中没有能够匹配任何模式的信息,当前进程会一直等到能够匹配的信息出现.等待时间也可以被指定:

iex> receive do
...>   {:hello, msg}  -> msg
...> after
...>   1_000 -> "nothing after 1s"
...> end
"nothing after 1s"

如果你想要的是已经在邮箱中的信息,可以将时限设置为0.

让我们使用这些来在进程间通信:

iex> parent = self()
#PID<0.41.0>
iex> spawn fn -> send(parent, {:hello, self()}) end
#PID<0.48.0>
iex> receive do
...>   {:hello, pid} -> "Got hello from #{inspect pid}"
...> end
"Got hello from #PID<0.48.0>"

当在用户界面中时,你会发现​flush/0​助手非常有用.它会刷新并打印邮箱中的所有信息.

iex> send self(), :hello
:hello
iex> flush()
:hello
:ok


Elixir spawn
Elixir 任务
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

Elixir 基本操作符

Elixir 二进制,字符串和字符列表

Elixir 类型规格与行为

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }