Learn Julia · 12/15

Concurrency & Parallelism

9 min read

Concurrency & Parallelism in Julia Concurrency and parallelism are about doing multiple things at the same time to make your programs faster and more efficient. 🚀

The Problem: Imagine you're at a coffee shop ☕. There's one barista (your computer's processor) taking an order, making the coffee, and then serving it. This is a sequential process. If there's a long line of customers, this single-threaded approach will be very slow. Everyone has to wait for the person in front of them to be fully served.

The Solution: Concurrency and parallelism are two ways to speed this up.

  • Concurrency: The barista can take an order, start brewing the coffee, and while the coffee is brewing, take the next person's order. The tasks are interleaved, making it seem like they are happening at the same time. This is great for tasks that involve waiting (like waiting for coffee to brew or a file to download).
  • Parallelism: The coffee shop hires more baristas. Now, multiple orders can be taken and multiple coffees can be made simultaneously. This is true parallel execution and is ideal for tasks that can be broken down into independent chunks of work.

Julia provides powerful and easy-to-use tools for both concurrency and parallelism. Let's dive in!

1. Asynchronous Programming: Tasks, @async, and @sync

Definition: Asynchronous programming is a way to handle tasks that might take a while to complete without blocking the main program. It's like our concurrent barista who takes another order while the coffee is brewing.

The Problem: In many applications, you need to perform long-running operations like reading a large file, making a network request, or querying a database. If you do this synchronously, your entire program will freeze and wait for that operation to finish. This leads to a poor user experience. Imagine a user interface that becomes completely unresponsive every time you click a button that fetches data from the internet!

How Julia Solves It: Julia uses Tasks for asynchronous operations. A Task is a unit of work that can be executed independently. The @async macro is used to start a task, and @sync is used to wait for all the asynchronous tasks within its block to complete.

Let's see it in action. Imagine we need to download two files from the internet. A naive, synchronous approach would look like this:

julia
function download_files_sequentially()
    println("Starting sequential download...")
    # Simulate downloading file 1 (takes 2 seconds)
    sleep(2)
    println("File 1 downloaded.")

    # Simulate downloading file 2 (takes 2 seconds)
    sleep(2)
    println("File 2 downloaded.")
    println("Sequential download finished.")
end

@time download_files_sequentially()

This will take about 4 seconds to complete because it downloads one file after the other. Now, let's do it asynchronously with @async and @sync.

julia
function download_files_asynchronously()
    println("Starting asynchronous download...")
    @sync begin
        @async begin
            # Simulate downloading file 1 (takes 2 seconds)
            sleep(2)
            println("File 1 downloaded.")
        end

        @async begin
            # Simulate downloading file 2 (takes 2 seconds)
            sleep(2)
            println("File 2 downloaded.")
        end
    end
    println("Asynchronous download finished.")
end

@time download_files_asynchronously()

This version will take only about 2 seconds! 🥳 Both downloads start at roughly the same time, and we only have to wait for the longest one to finish. The @sync block ensures that the program waits for both @async tasks to complete before printing "Asynchronous download finished."

Under the Hood: Julia's Task scheduler is cooperative. This means a task will keep running until it explicitly yields control (e.g., by calling sleep(), yield(), or waiting for I/O). This is different from pre-emptive scheduling where the operating system can interrupt a task at any time.

Interesting Fact: The concept of coroutines, which Tasks are a form of, has been around since the late 1950s! They were a key feature of the Simula programming language, which is considered the first object-oriented programming language.

2. Multi-threading Basics: Threads.@threads

Definition: Multi-threading is a form of parallelism where multiple threads of execution run within the same process. They share the same memory space, which makes communication between threads easy but also introduces potential dangers.

The Problem: Some computational tasks are just plain heavy. Think of processing a large image, running a complex simulation, or training a machine learning model. Even with asynchronous operations, if the task itself is CPU-bound (meaning it's constantly doing calculations), a single core of your processor will be maxed out.

How Julia Solves It: Julia has built-in support for multi-threading. You can start Julia with multiple threads, and then use the Threads.@threads macro to easily parallelize a for loop.

Getting Started: To use multi-threading, you need to start Julia with a specific number of threads. You can do this from the command line:

bash
julia -t 4

This starts Julia with 4 threads. The -t auto option is also available to use as many threads as you have CPU cores. You can check the number of available threads within a Julia session with Threads.nthreads().

Now, let's look at an example. Imagine we want to perform a heavy computation on each element of a large array.

julia
function heavy_computation(x)
    # A placeholder for a complex calculation
    sleep(0.1)
    return x^2
end

function process_array_sequentially(arr)
    result = similar(arr)
    for i in eachindex(arr)
        result[i] = heavy_computation(arr[i])
    end
    return result
end

function process_array_parallel(arr)
    result = similar(arr)
    Threads.@threads for i in eachindex(arr)
        result[i] = heavy_computation(arr[i])
    end
    return result
end

my_array = 1:12

println("Sequential processing:")
@time process_array_sequentially(my_array)

println("\nParallel processing with $(Threads.nthreads()) threads:")
@time process_array_parallel(my_array)

If you run this with multiple threads, you'll see a significant speedup in the parallel version. The Threads.@threads macro automatically divides the loop iterations among the available threads.

Industry Practice: Threads.@threads is fantastic for simple, "embarrassingly parallel" for loops where each iteration is independent of the others. For more complex parallel patterns, you might need to use lower-level threading primitives like Threads.@spawn.

3. Distributed Computing Introduction (Distributed.jl)

Definition: Distributed computing involves running a program on multiple machines (or processes) that communicate over a network. Each process has its own memory space.

The Problem: What if your computation is so massive that it doesn't fit into the memory of a single computer, or it would take a single computer years to complete? Multi-threading helps, but it's limited by the number of cores on one machine.

How Julia Solves It: Julia's Distributed module, which is part of the standard library, makes it surprisingly easy to manage and coordinate work across multiple processes, whether they are on the same machine or on different machines in a cluster.

Getting Started: You can add worker processes from within Julia or when you start it up.

From the command line:

bash
julia -p 4

This starts a Julia session with 4 local worker processes.

From within a Julia session:

julia
using Distributed

# Add 4 local worker processes
addprocs(4)

# You can also add processes on remote machines
# addprocs([("worker1.example.com", 2), ("worker2.example.com", 2)])

The @distributed macro can be used to parallelize a for loop across these worker processes. A common pattern is to use a "reducer" function to combine the results from each process.

julia
using Distributed

@everywhere function is_prime(n)
    if n <= 1
        return false
    end
    for i in 2:isqrt(n)
        if n % i == 0
            return false
        end
    end
    return true
end

function count_primes_distributed(range)
    return @distributed (+) for n in range
        is_prime(n) ? 1 : 0
    end
end

# Make sure the is_prime function is available on all worker processes
@everywhere using Primes # A more robust way if it were in a module

println("Counting primes up to 1,000,000 on $(nworkers()) worker processes...")
@time count_primes_distributed(1:1_000_000)

In this example, @distributed (+) tells Julia to execute the loop in parallel on the worker processes and then combine the results by adding them up (+ is the reducer). The @everywhere macro ensures that our is_prime function is defined on all the worker processes.

Fun Fact: The Julia language was used to parallelize the Celeste project, which cataloged 188 million astronomical objects. By using 650,000 cores on a supercomputer, a task that was estimated to take decades was completed in just 14.6 minutes!

4. Avoiding Race Conditions and Memory Issues

Definition: A race condition occurs when multiple threads or processes access shared data and try to change it at the same time. The final result depends on the unpredictable timing of which thread "wins" the race.

The Problem: Imagine two threads trying to update a shared counter.

  1. Thread A reads the current value of the counter (let's say it's 5).
  2. Thread B reads the current value of the counter (it's also 5).
  3. Thread A adds 1 to its value (now it has 6) and writes it back to the counter.
  4. Thread B adds 1 to its value (it also has 6) and writes it back to the counter.

The counter should be 7, but it's 6. This is a classic race condition. These bugs are notoriously difficult to find because they can be intermittent and hard to reproduce. 🐛

How to Avoid Them:

  • Locks: The most common way to prevent race conditions is to use locks. A lock ensures that only one thread can access a particular piece of code or data at a time. In Julia, you can create a ReentrantLock and use the lock and unlock functions, or more conveniently, the lock block syntax.

    julia
    using Base.Threads
    
    counter = Atomic{Int}(0) # Using an Atomic is even better for simple counters!
    lock_for_complex_data = ReentrantLock()
    complex_data = Dict("key" => 0)
    
    # Using Atomics for simple types is the most efficient way
    @threads for i = 1:1000
        atomic_add!(counter, 1)
    end
    println("Atomic counter: ", counter[])
    
    # Using a lock for more complex data structures
    @threads for i = 1:1000
        lock(lock_for_complex_data) do
            # This block is a critical section
            complex_data["key"] += 1
        end
    end
    println("Locked Dict value: ", complex_data["key"])
  • Atomics: For simple operations on primitive types like integers, Julia provides Atomic types. Operations on these types (like atomic_add!) are guaranteed to be "atomic," meaning they happen all at once without being interrupted. This is much more efficient than using a lock for simple counters.

  • Immutable Data: If data is never changed after it's created (it's immutable), then it's safe for multiple threads to read it at the same time without any locks. This is a core principle of functional programming and a great way to avoid concurrency issues.

  • Channels: For communication between tasks or threads, especially in more complex producer-consumer scenarios, Channels are an excellent choice. They provide a thread-safe way to pass messages.

Practical Advice:

  • Keep shared data to a minimum. The less data you share, the fewer opportunities there are for race conditions.
  • When you do need to share data, prefer atomics for simple counters and locks for more complex data structures.
  • The Threads.@threads macro is generally safe if each iteration of the loop is independent and writes to a unique location in a shared array.

By understanding and using these tools, you can harness the full power of modern hardware to make your Julia programs fly! ✈️


Further Reading and References

Challenge

You are tasked with building a system that fetches data from multiple remote endpoints concurrently to improve performance. Each API call has a variable delay, and you need to collect all the results into a single shared dictionary.

Your challenge is to complete the process_requests_concurrently function to achieve this.

Requirements:

  1. The function must process the list of API calls provided in the api_calls variable.
  2. Use the @async macro to launch each mock_api_call concurrently so they run in an interleaved manner.
  3. Use the @sync block to ensure your main program waits for all the asynchronous tasks to complete before proceeding.
  4. The results from each API call must be used to update the shared results dictionary. The key should be the endpoint id, and the value should be the data.
  5. Crucially: Accessing the shared results dictionary from multiple concurrent tasks can lead to a race condition. You must implement a synchronization mechanism, such as a ReentrantLock, to ensure that the dictionary is updated safely, preventing any data corruption.

Expected result

Your code should produce output that demonstrates concurrent execution and safe data aggregation.

  1. The console will first print the "Fetching from endpoint..." messages for all three endpoints in quick succession.
  2. The "...done fetching..." messages will appear based on the delay, not the initial order. You should see the message for endpoint 2 (0.5s delay) first, then endpoint 3 (1.0s), and finally endpoint 1 (1.5s).
  3. The @time macro will report an execution time of approximately 1.5 seconds (the duration of the longest task), proving that the operations did not run sequentially (which would have taken 3.0 seconds).
  4. Finally, the program will print the results dictionary, which should contain three entries. For example:
jboss-cli
Starting concurrent processing...
Fetching from endpoint 1...
Fetching from endpoint 2...
Fetching from endpoint 3...
...done fetching from endpoint 2.
...done fetching from endpoint 3.
...done fetching from endpoint 1.
  1.510115 seconds (16.22 k allocations: 859.391 KiB)
Concurrent processing finished.

Final aggregated results:
Dict(2 => 0.12345, 3 => 0.67890, 1 => 0.11121)

Note: The exact timing and the random data values will vary with each execution.

julia

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.