LoginSignup
2
0

More than 1 year has passed since last update.

paiza.ioでelixir その49

Posted at

概要

paiza.ioでelixirやってみた。
Task使ってみた。

サンプルコード

1..100
|> Stream.take(10)
|> Task.async_stream(fn i ->
	Process.sleep(10)
	IO.puts(to_string(i))
end)
|> Enum.to_list()
|> IO.inspect

task = Stream.interval(100) 
|> Task.async_stream(&(&1))
|> Enum.take(5)
Enum.map(task, &(IO.inspect(&1)))

task = Task.async(fn -> 
	1 + 1 
end)
Task.await(task)
|> IO.inspect

tasks = [Task.async(fn -> 
	1 + 1 
end), Task.async(fn -> 
	2 + 3 
end)]
Task.await_many(tasks)
|> IO.inspect

tasks =
	for i <- 1..10 do
		Task.async(fn ->
			Process.sleep(i * 5)
			i
		end)
	end
tasks_with_results = Task.yield_many(tasks, 1000)
results =
	Enum.map(tasks_with_results, fn {task, res} ->
		res || Task.shutdown(task, :brutal_kill)
	end)
for {:ok, value} <- results do
	IO.inspect(value)
end

実行結果

1
2
3
4
5
6
7
8
9
10
[
  ok: :ok,
  ok: :ok,
  ok: :ok,
  ok: :ok,
  ok: :ok,
  ok: :ok,
  ok: :ok,
  ok: :ok,
  ok: :ok,
  ok: :ok
]
{:ok, 0}
{:ok, 1}
{:ok, 2}
{:ok, 3}
{:ok, 4}
2
[2, 5]
1
2
3
4
5
6
7
8
9
10

成果物

以上。

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0