Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 38 ยท Applications

Concurrency and Places

Compare Racket's green threads, channels, synchronization with sync, futures and places for parallelism, with runnable JavaScript stand-ins for channels and a worker pool.

Programs often have to do several things at once: wait for the network while updating a screen, or crunch numbers on every core. Racket offers several tools, and choosing the right one starts with a distinction. Concurrency is about structuring a program as independent activities that take turns. Parallelism is about using several processor cores at the same time. Racket has separate features for each.

This lesson surveys threads, channels and events, then futures and places, with a JavaScript stand-in for the message-passing style. It connects to generators and coroutines: threads are a kind of coroutine that the runtime schedules for you.

Racket cannot run in our editor, so the Racket code is read-only, and I do not claim output for timing-dependent code. The runnable code is JavaScript stand-ins using promises and async functions, which model message passing but not Racket's preemptive threads.

Threads: lightweight, preemptive, not parallel

thread starts a new thread that runs a function concurrently with the rest of the program:

RACKET
(define t
  (thread (lambda ()
            (for ([i 3])
              (displayln (format "worker ~a" i))
              (sleep 0.1)))))

(displayln "main continues")
(thread-wait t)   ; block until the thread finishes

Racket threads are green threads: scheduled by the Racket runtime, cheap (you can start many thousands) and preemptive, meaning the runtime switches between them, so a loop cannot starve the others. They share one OS thread, so they do not run in parallel; their purpose is concurrency, such as handling many connections. The exact interleaving of the output above depends on timing, which is why you should never rely on it.

Channels and sync

Threads should communicate by sending messages, not by sharing mutable variables. A channel is a rendezvous point: channel-put blocks until another thread does channel-get, and vice versa.

RACKET
(define ch (make-channel))

(thread (lambda ()
          (for ([i 3])
            (channel-put ch (* i i)))
          (channel-put ch 'done)))

(let loop ()
  (define v (channel-get ch))
  (unless (eq? v 'done)
    (displayln v)
    (loop)))
;; prints 0, 1, 4 in order

This is the producer/consumer pattern without locks: because the put and get meet, order is deterministic here. Everything that can be waited on in Racket is an event, including channels, threads, timers (alarm-evt), input ports and semaphores. The function sync waits for one of several events to be ready, and choice-evt/handle-evt compose them:

RACKET
(sync (handle-evt ch (lambda (v) (list 'got v)))
      (handle-evt (alarm-evt (+ (current-inexact-milliseconds) 1000))
                  (lambda (_) 'timeout)))

That is a receive with a one-second timeout, written declaratively. For shared state, Racket also has semaphores and make-semaphore/call-with-semaphore, but message passing is usually clearer.

Stand-in: channels with async/await

JavaScript runs on one thread with an event loop, and a promise-based channel gives a similar rendezvous. This stand-in builds an unbuffered channel with put and get that wait for each other, runs a producer and a consumer, and prints deterministic output.

JS Stand-in: an unbuffered channel

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because the channel is unbuffered, each put completes only when a get takes the value, which is the same rendezvous behavior as Racket's channels.

Futures and places: real parallelism

For parallel speed-up on multiple cores, Racket provides two tools:

  • Futures (future, touch) run a function in parallel on another OS thread, but only while it sticks to simple operations (for example, floating-point math and fixnum arithmetic). The first time it needs something the runtime cannot do in parallel (such as certain allocations or I/O), it blocks until touch picks it up. Racket CS handles more operations in parallel than older versions, but the rule remains: futures are best for tight numeric loops.
  • Places (dynamic-place, place) start a new Racket instance with its own memory, communicating only by message passing over place channels (place-channel-put, place-channel-get). Nothing is shared, so there are no data races. Use places for large independent jobs, such as processing different files.
RACKET
(require racket/place)

(define (start-worker)
  (place ch
    (define n (place-channel-get ch))
    (place-channel-put ch (for/sum ([i (in-range n)]) i))))

(define p (start-worker))
(place-channel-put p 1000000)
(place-channel-get p)   ; => 499999500000

The place form creates a module-level worker that runs in parallel; messages are copied between places. Compare this to futures: a future shares memory with its parent and is lightweight, a place is heavier but isolated and safe for any code.

flowchart LR
  subgraph Concurrency["Concurrency (one OS thread)"]
    T1["thread A"] <-->|"channel"| T2["thread B"]
  end
  subgraph Parallel["Parallelism (many cores)"]
    P1["place 1"] -->|"place channel"| P2["place 2"]
    F["future"] --- P1
  end

Threads share one core and communicate via channels; places and futures use extra cores.

Stand-in: a worker pool

This block models splitting work across "workers" that report back by message, with a deterministic reduction at the end. It runs in one JavaScript thread (as the stand-in for places), but the structure of the code is what you would write with places.

JS Stand-in: splitting work and collecting messages

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Choosing a tool

  • Many independent activities that mostly wait (servers, GUIs): threads and channels.
  • Number crunching in a tight loop: futures.
  • Large isolated tasks that must use all cores: places.
  • Coordinating timeouts and multiple sources: sync with events.
  • Shared mutable state: avoid it; if unavoidable use semaphores and keep critical sections tiny.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Do Racket threads run in parallel on several cores?

    Racket threads give concurrency, not parallel speed-up. Futures and places use more cores.
  2. 2. What does channel-put do when no thread is receiving?

    Channels are rendezvous points: both sides must be ready.
  3. 3. What does sync do?

    sync waits on events such as channels, timers or ports; handle-evt transforms each result.
  4. 4. How do places communicate?

    Each place has its own memory, so messages are copied through place channels.

Summary

  • Concurrency (threads) structures activities; parallelism (futures, places) uses multiple cores.
  • Racket threads are cheap and preemptive but share one OS thread.
  • Channels and sync give message passing and timeouts without locks.
  • Futures suit numeric loops; places provide isolated parallel workers.
  • Prefer messages over shared mutable state.

Next: Drawing with pict