Available

amalgame-threading

Mutex, Channel, ThreadSpawn — wraps pthread.

amc package add threading GitHub ↗ ← Back to the ecosystem

Overview

Concurrency primitives: threads, mutexes, bounded FIFO channels. Wraps pthread on Linux and macOS; on Windows, MSYS2 / MinGW provides pthread-w32. Native Windows threads are planned for v2. Every thread is registered with the Boehm GC.

Features

  • ✓Threading.ThreadSpawn(fn, arg), ThreadJoin(t), ThreadSleep(ms), ThreadIsAlive(t)
  • ✓Threading.MutexNew(), MutexLock(m), MutexUnlock(m), MutexTryLock(m)
  • ✓Bounded FIFO Threading.ChannelNew(capacity): ChannelSend, ChannelReceive, ChannelClose, plus non-blocking Try… variants
  • ✓Internal condition variables for Channel
  • ✓GC-safe registration via GC_pthread_create

Example

Minimal usage example — copy-paste runnable after install.

amc package add threading

import Amalgame.Threading

class Program {
    public static void Main() {
        let ch: AmalgameChannel = Threading.ChannelNew(16)   // bounded FIFO

        let worker = (n: int) => {
            var i: int = 1
            while (i <= n) {
                Threading.ChannelSend(ch, i * i)
                i = i + 1
            }
            Threading.ChannelClose(ch)
            return 0
        }
        let t = Threading.ThreadSpawn(worker, 10)   // runs worker(10) on a new thread

        while (true) {
            let v: int = Threading.ChannelReceive(ch)
            if (v == 0 && Threading.ChannelIsClosed(ch)) { break }   // 0: closed and empty
            Console.WriteLine(String_FromInt(v))
        }
        Threading.ThreadJoin(t)
    }
}

At a glance

Related packages