Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Elixir Concurrency Model #28

Open
samhstn opened this issue Mar 4, 2017 · 0 comments
Open

Elixir Concurrency Model #28

samhstn opened this issue Mar 4, 2017 · 0 comments
Labels
enhancement New feature or enhancement of existing functionality

Comments

@samhstn
Copy link
Member

samhstn commented Mar 4, 2017

Simple example of the Elixir Concurrency Model and how to handle blocking processes.

Paste the below code into a file called concurrency_demo.ex and run
$ elixir concurrency_demo.ex to run the example locally

defmodule Log do
  defp log(arg), do: IO.puts arg
  def first, do: log "first"
  def second, do: log "second"
  def slowfirst do
    :timer.sleep(1000)
    first()
  end
end

IO.puts "RUN 1"
Log.slowfirst()
Log.second()

# Outputs:
# $ RUN 1
# $ first
# $ second

# In "RUN 1" we see that `slowfirst` blocks `second` from running

IO.puts "RUN 2"
task = Task.async(fn -> Log.slowfirst() end)
Log.second()

# Outputs:
# $ RUN 2
# $ second
# $ first

# But in "RUN 2" we start `slowfirst` and then carry on with the script

Task.await(task) # If you don't assign task and `await`, the program will finish and you won't see the log
@samhstn samhstn added the enhancement New feature or enhancement of existing functionality label Mar 4, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or enhancement of existing functionality
Projects
None yet
Development

No branches or pull requests

1 participant