Created
October 1, 2018 12:13
-
-
Save shoz-f/2e5097701ef6f23fc08284f45fcfb468 to your computer and use it in GitHub Desktop.
プリミティブなプロセスで実装
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| defmodule StopwatchB do | |
| import System, only: [ monotonic_time: 1 ] | |
| @gclock __MODULE__ | |
| def activate() do | |
| now = monotonic_time(100) | |
| pid = spawn(StopwatchB, :watch_loop, [now]) | |
| Process.register(pid, @gclock) | |
| :ok | |
| end | |
| def watch_loop(last_time) do | |
| receive do | |
| {:restart, caller} -> | |
| now = monotonic_time(100) | |
| send caller, {:ok, now - last_time} | |
| watch_loop(now) | |
| {:lap, caller} -> | |
| now = monotonic_time(100) | |
| send caller, {:ok, now - last_time} | |
| watch_loop(last_time) | |
| end | |
| end | |
| def restart() do | |
| send @gclock, {:restart, self()} | |
| receive do | |
| {:ok, time} -> time | |
| end | |
| end | |
| def lap() do | |
| send @gclock, {:lap, self()} | |
| receive do | |
| {:ok, time} -> time | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment