Go-flavored concurrency in C
Anton Zhiyanov<br>projects<br>books<br>blog<br>about
Go's concurrency is one of the main reasons people like the language. You write go f(), send values through channels, and the runtime scheduler runs thousands of goroutines on just a few OS threads. It feels effortless.<br>None of that machinery exists in C. Which made me wonder: how close can you get to Go's concurrency model using only POSIX threads? Obviously, native OS threads can't match the efficiency of lightweight goroutines, but what is the actual cost, when does it become a problem, and is there any way to at least partially avoid it?<br>I ran into these questions while adding concurrency to Solod (So), a strict subset of Go that translates to plain C, with no runtime and no garbage collector. In the end, I came to the conclusion that you can do quite a lot with pthreads — as long as you're honest about the tradeoffs.<br>This post is about the POSIX threads-based concurrency model I chose, the benefits it offers, and its limitations.<br>Mutex/Cond •<br>Atomics •<br>Pool •<br>Channel •<br>Performance •<br>Design •<br>Wrapping up<br>Mutex/Cond<br>Everything in So's concurrency stack is built on two basic POSIX primitives: the mutex and the condition variable. sync.Mutex is a thin wrapper around pthread_mutex_t:<br>// Extracted from So's stdlib source code.<br>type Mutex struct {<br>mu pthread_mutex_t
func (m *Mutex) Lock() {<br>rc := pthread_mutex_lock(&m.mu)<br>if rc != 0 {<br>panic("sync: Mutex.Lock failed")
Since So translates to C, this is basically a struct that holds a pthread_mutex_t and a function that calls pthread_mutex_lock. Here's the transpiler output:<br>// The translated C code.<br>typedef struct sync_Mutex {<br>pthread_mutex_t mu;<br>} sync_Mutex;
void sync_Mutex_Lock(sync_Mutex* m) {<br>int rc = pthread_mutex_lock(&m->mu);<br>if (rc != 0) {<br>so_panic("sync: Mutex.Lock failed");
That is the whole translation — the generated C is a near-mechanical mirror of the So code, only noisier. From here on, I'll mainly show the So version, but I'll also provide the C code for those who are interested.
There's nothing exciting here: sync.Mutex is a pthread mutex wrapper that panics if something goes wrong (which is rare).<br>The companion primitive is sync.Cond, a wrapper around pthread_cond_t. It's the standard "wait until a condition holds" tool, associated with a mutex:<br>type Cond struct // wraps pthread_cond_t + pthread_mutex_t<br>func (c *Cond) Wait() // wraps pthread_cond_wait<br>func (c *Cond) Signal() // wraps pthread_cond_signal<br>func (c *Cond) Broadcast() // wraps pthread_cond_broadcast
Show the translated C codetypedef struct sync_Cond {<br>pthread_cond_t cond;<br>sync_Mutex* mu;<br>} sync_Cond;
void sync_Cond_Wait(sync_Cond* c); // wraps pthread_cond_wait<br>void sync_Cond_Signal(sync_Cond* c); // wraps pthread_cond_signal<br>void sync_Cond_Broadcast(sync_Cond* c); // wraps pthread_cond_broadcast
These two types — Mutex and Cond — are the foundation. Other concurrency tools — Once, the thread pool, channels — are built using a mutex and one or more condition variables. This has several effects on performance, as we'll see later.<br>Atomics<br>Not everything needs a lock. So's sync/atomic mirrors Go's: Bool, Int32, Int64, Uint32, Uint64, and a generic Pointer[T], all with Load, Store, Swap, and CompareAndSwap methods.<br>The nice thing is that these don't need pthreads at all. They map directly to the C compiler's __atomic builtins — the same hardware instructions that Go's compiler emits. So there's no reason for them to be any slower, and they're not:<br>Atomic opGoSoWinnerLoad2ns2ns~sameStore2ns2ns~sameCompareAndSwap13ns13ns~sameEach number is the cost of one operation on a single thread.
sync.Once is a good example of using atomics effectively. Its fast path only needs a single atomic load — after the given function runs, every future call to Do checks a flag and returns:<br>type Once struct {<br>mu Mutex<br>done atomic.Bool
// Do calls f if and only if Do is being called<br>// for the first time for this o.<br>func (o *Once) Do(f func()) {<br>if o.done.Load() { // lock-free fast path<br>return<br>// slow path...
Show the translated C codetypedef struct sync_Once {<br>sync_Mutex mu;<br>atomic_Bool done;<br>} sync_Once;
// Do calls f if and only if Do is being called<br>// for the first time for this o.<br>void sync_Once_Do(sync_Once* o, void (*f)()) {<br>if (atomic_Bool_Load(&o->done)) { // lock-free fast path<br>return;<br>// slow path...
Worker pool<br>To actually run code concurrently, you need threads. The conc.Thread type wraps pthread_t and its related functions:<br>type Thread struct // wraps pthread_t<br>func (th Thread) Wait() any // wraps pthread_join<br>func (th Thread) Detach() // wraps pthread_detach
Show the translated C codetypedef struct conc_Thread {<br>pthread_t t;<br>} conc_Thread;
void* conc_Thread_Wait(conc_Thread th); // wraps pthread_join<br>void conc_Thread_Detach(conc_Thread th); // wraps pthread_detach
Consider this conc.Go function:<br>// Go launches an OS thread that runs fn(arg) and returns a handle to it.<br>func Go(entry func(any) any, arg any)...