1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

paiza.ioでelixirAdvent Calendar 2022

Day 25

paiza.ioでelixir その50

Last updated at Posted at 2022-11-08

概要

paiza.ioでelixirやってみた。
練習問題やってみた。

練習問題

マルチタスクを実装せよ。

サンプルコード

defmodule Tsk0 do
	def tick(agent, interval \\ 50) do
		cast(agent)
		:timer.sleep(interval)
		tick(agent, interval)
	end
	def start(agent) do
		Agent.start(fn -> 
			[0] 
		end, name: agent)
	end
	def cast(agent) do
		Agent.update(agent, __MODULE__.succ())
		IO.puts("task0")
	end
	def get(agent) do
		Agent.get(agent, &(&1))
	end
	def succ() do
		fn(l) -> 
			[hd(l) + 1 | l] 
		end
	end
end
defmodule Tsk1 do
	def tick(agent, interval \\ 100) do
		cast(agent)
		:timer.sleep(interval)
		tick(agent, interval)
	end
	def start(agent) do
		Agent.start(fn -> 
			[0] 
		end, name: agent)
	end
	def cast(agent) do
		Agent.update(agent, __MODULE__.succ())
		IO.puts("task1")
	end
	def get(agent) do
		Agent.get(agent, &(&1))
	end
	def succ() do
		fn(l) -> 
			[hd(l) + 1 | l] 
		end
	end
end
defmodule Tsk2 do
	def tick(agent, interval \\ 200) do
		cast(agent)
		:timer.sleep(interval)
		tick(agent, interval)
	end
	def start(agent) do
		Agent.start(fn -> 
			[0] 
		end, name: agent)
	end
	def cast(agent) do
		Agent.update(agent, __MODULE__.succ())
		IO.puts("task2")
	end
	def get(agent) do
		Agent.get(agent, &(&1))
	end
	def succ() do
		fn(l) -> 
			[hd(l) + 1 | l] 
		end
	end
end

Tsk0.start(Foo) 
|> IO.inspect
Tsk1.start(Foo1) 
|> IO.inspect
Tsk2.start(Foo2) 
|> IO.inspect
Task.async(fn -> 
	Tsk0.tick(Foo) 
end) 
Task.async(fn -> 
	Tsk1.tick(Foo1) 
end) 
Task.async(fn -> 
	Tsk2.tick(Foo2) 
end) 
:timer.sleep(300)


実行結果

{:ok, #PID<0.101.0>}
{:ok, #PID<0.102.0>}
{:ok, #PID<0.103.0>}
task0
task1
task2
task0
task1
task0
task0
task2
task1
task0
task0
task1
task0

以上。

1
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?