dwyl / dwyl/learn-elixir

Elixir Concurrency Model

Open
#28 0 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Elixir
Stars
1.7k
Forks
112
PR merge metrics
No merged PRs in 30d

Description

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

```elixir
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
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.