Threaded application in elixir language

Elixir language has no static/compile-time type checking like F#,Scala;ADA.
Exilir language is used in telecom applications , by discord , by pinterest.
It is ideal for threaded applications
Ok , let's start.
Run:
Code:
mix new test
cd test

In the directory lib put the file Main2.Ex :
Code:
defmodule Main3 do

def startme do
    # Run a long-running computation concurrently
    task = Task.async(fn ->
        # Simulate work
        :timer.sleep(1000)
        42
    end)

    # Do other things here...
    IO.puts("Main process is free to work!")
    # Retrieve the result (blocks until the task finishes)
    result = Task.await(task)
    IO.puts("The answer is #{result}")
end

end

Run:
Code:
mix compile
mix run -e "Main3.startme()"

Et voila.
 
It's also a useful scripting language. Converting your example to a single-file EXS script and returning JSON looks like this:

sh:
$ cat main3.exs
#!/usr/bin/env -S ERL_FLAGS=+B elixir

Mix.install([
  {:jason, "~> 1.4"}
])

defmodule Main3 do
  def startme do
    # Run a long-running computation concurrently
    task = Task.async(fn ->
        # Simulate work
        :timer.sleep(1000)
        Jason.encode!(%{answer: 42})
    end)

    # Do other things here...
    IO.puts("Main process is free to work!")

    # Retrieve the result (blocks until the task finishes)
    result = Task.await(task)
    IO.puts("The answer is #{result}")
  end
end

Main3.startme()

The first run will download and cache the required libraries (JSON in this case):

sh:
$ chmod +x main3.exs
$ ./main3.exs
Resolving Hex dependencies...
Resolution completed in 0.053s
New:
  jason 1.4.4
* Getting jason (Hex package)
==> jason
Compiling 10 files (.ex)
Generated jason app
Main process is free to work!
The answer is {"answer":42}

Future runs use the cached libs:

sh:
$ ./main3.exs
Main process is free to work!
The answer is {"answer":42}
 
Back
Top