r/ProgrammingLanguages • Bau • 1d ago

Requesting criticism Multithreading for a Reference-Counted Language without Annotations

I'm working on "Bau" (link in a comment), a small, memory-safe systems language that transpiles to C. It uses reference counting and automatic borrow (most reads don't touch counts). Types declared owned have a single owner and no ref count, and are faster. I want to add multithreading support, and would like to get feedback on my design.

Goals

  • No annotations, lifetimes, Send/Sync, async. Any thread can read and write any object.

  • Memory safe, but data races are allowed, as in Java.

  • Single-threaded programs have no overhead; a small overhead for shared objects.

How it should work

  • Each object has a hidden shared bit in the ref-count field. Objects start local: non-atomic counts, as today. When an object is stored where another thread can reach it (global, channel, etc.), the shared bit is set in this and all referenced objects, recursively. I think this is like Lean 4. I know setting the bit can take time (same as freeing up a large graph recursively).

  • Shared objects use atomic counts, and atomic exchanges for pointer stores.

  • Borrowed reads stay count-free and lock-free. To do this, if the ref count of a shared object becomes zero, objects are not immediately freed, but only after a grace period, similar to Linux RCU.

  • Epoch based reclamation (EBR) is used. There are no safepoint polls (as in QSBR), but there is a bookkeeper thread that keeps track of the epoch and uses a process-wide barrier (membarrier).

  • Mutable owned objects move between threads. Storing them where several threads can reach them is a compile error. Types can be const which means all fields are immutable after construction; those can be shared freely.

Compared to...

  • Go: Go isn't memory safe under data races (torn interfaces and slices), and has a tracing GC.

  • Swift: uses atomic counts always, not only for shared objects.

  • Rust: needs lifetimes and Send/Sync, Rc, Arc. My language doesn't need those annotations.

  • Java: has the same safety contract, but uses more memory and has pauses due to tracing GC.

  • Lean 4, Koka: my language is primarily imperativ.

Disadvantages

  • Not data-race free: racy programs can give weird / wrong answers, as in Java. const types (which are opt-in) can prevent this.

  • Sharing is invisible: one store into a global can make a large graph shared, and slower.

  • close() of a shared object may run on another thread, a few milliseconds late. Or then, is bit slower (never borrows, and disallow owned).

Questions

  1. Is "memory safe, but not data-race free" the right trade-off for a simple language?

  2. Implicit sharing hides the fast/slow split. Would you prefer an explicit shared marker, or is tooling enough?

  3. Setting the shared bit is O(n). Can this be a problem?

  4. Has anyone shipped asymmetric fences (membarrier, FlushProcessWriteBuffers) in a language runtime?

  5. Is a non-deterministic close() acceptable for shared objects? Alternatively I could use refcounts here, always.

  6. What did I miss? Prior art I know: CPython free-threading (PEP 703), Lean 4, Koka, Linux RCU.

15 Upvotes

15 comments sorted by

12

u/stumpychubbins 1d ago

My two cents is that preventing data races should be the absolute bare minimum for a modern language and it’s embarrassing that Go doesn’t. If I were you, I’d use Swift's approach for now and put together a basic design for something more complex as a follow-up. Always-atomic can serve as a baseline that you can benchmark other approaches against.

5

u/Tasty_Replacement_29 Bau 1d ago edited 1d ago

There are multiple types of races:

  • (A) Data races in (fat) pointers. This is possible in the Go memory model. You can corrupt the slice length, and so can do out-of-bound writes. In theory, this allows RCE (Remote Code Execution). This would be hard, but with the help of AI I think it's possible to construct exploits.

  • (B) Data races in (as an example) integer arrays, so that multiple threads can overwrite each others changes concurrently. This is possible in the Java memory model. Memory safety it guaranteed (no out-of-bound writes). Behavior might be surprising, and so you could have bugs due to that.

  • (C) No data races are possible by default in Rust and Swift and (most) functional languages. (This doesn't mean you can't have bugs or deadlocks or panics etc. in those languages).

Currently my plan is (B) by default, because (C) is not as developer-friendly.

2

u/Quote_Revolutionary 5h ago

if you have an array of pointers though a data race of B can end up as a data race of A unless you always use atomic operations for the update of pointers, this however means that you cannot have pointers that go beyond 64 bits

1

u/Tasty_Replacement_29 Bau 3h ago

Yes. Some languages like Go have "fat pointers", where the length or type is stored separately from the pointer. That's why Go has the memory issue I mentioned: Go isn't memory safe under data races. For my language, pointers are 64 bit.

2

u/stumpychubbins 4h ago

Right, sorry I should’ve been more specific. What I meant with data races is that any modern language should prevent, at bare minimum, split reads/writes of a semantically unsplittable value. Preventing split reads/writes means that a reader should see the result of precisely one write. If you explicitly write only the length of a slice and then the pointer of a slice, it’s ok for a reader to see the value in the middle of that operation (since that’s unsafe anyway). If you overwrite the whole slice, the reader should only see either the previous slice or the overwritten slice. When I last used C#, split reads/writes were possible for scalars. Like, you could write 0xffff to a uint16 holding 0 and a reader could, in theory, see 0xff00. I never wrote multithreaded code in Java but I’d guess it’s the same. Personally I love Rust's model where you need to be very explicit about the semantics of shared data, but it doesn’t work for every language.

I think you should ensure that data races can’t cause memory unsafety or split reads/writes, but otherwise it’s fine to be less strict than Rust.

2

u/Tasty_Replacement_29 Bau 3h ago

You are right! Now I see that in both the Java and C# memory model, writes to 64-bit long and double are allowed to tear (in Java, this can be prevented via volatile keyword). I didn't know this.

(With modern 64-bit hardware, there are no tears in reality, but other hardware and the specification allows this.)

1

u/stumpychubbins 1h ago

Yeah I sadly learned it the hard way, it was no fun being a 17 year old at my first real programming job having to debug why a number was none of the values I was setting it to. I’ll probably remember that fun fact forever.

Maybe you can make your backend always use atomics for scalar size/architecture combos that can cause tearing, even if it pessimises performance? That feels like a reasonable default and it prevents the worst heisenbugs. I think it’s ok to expect the programmer to just know to use a mutex or whatever if they have more complex sets of values that need to be kept in sync, so long as you keep your core types atomic-by-default.

1

u/SkiFire13 2h ago

Note that implementing B correctly is very subtle, and in general I don't believe it's possible to do it without some kind of GC.

For example you stated that you use reference counting with atomic swaps. Consider what could happen when thread A is trying to read an object and thread B is trying to write to it, and that object currently has a refcount of 1:

  • thread A loads the pointer

  • thread B performs the swap

  • thread B decreases the refcount of the old pointer, it's now 0

  • thread B frees the old pointer

  • thread A tries to increase the refcount => use after free

The issue is that acquiring a reference count and eagerly freeing a reference counted pointer when the count reaches 0 is a fundamentally unsafe combination of operations. Of course you don't want to get rid of the former, so the latter has to go, and you cannot free eagerly. The alternative is delayed freeing, also technically called "memory reclamation scheme", which is generally either very costly, or it's a full GC.

4

u/garagedragon 23h ago

I don't see how you can maintain memory safety if you're not tracking whether a read borrow of a shared object still exists before you reclaim it. "Only after a grace period" is going to reduce the chances of something going wrong, but can't eliminate the possibility that say, a thread holding a borrow sleeps for a long time (perhaps waiting on something else) before trying to use it.

If you're preventing this by having a distinction between the borrow and the "owning" shared reference ala Rust's Arc, you also need to ensure the former can't outlive the latter.

2

u/Tasty_Replacement_29 Bau 23h ago

There is tracking; this is not best effort. (I didn't invent this part, I'm just using an already existing mechanism - I didn't know about them before starting on this topic.) There are two possible ways:

I'm planning to use EBR: before each borrow, there is a "pin" of the thread to the current epoch, and "unpin" after the borrow. These are writes to the thread local storage (inlined, not method calls). QSBR would be slightly different, and might have lower overhead, but it requires a "ping" from time to time from each thread, and so requires code in each loop in the header of each function call. Also, in my case there is a special bookkeeper thread that keeps track of the epoch and uses membarrier() or similar (depening on the platform) so that fence is not needed in each thread.

I want my language to be significantly easier to use than Rust, and that's why I want to avoid annotations etc.

2

u/pthierry 19h ago

What is the goal of your language if it doesn't guarantee the absence of data races? That is, if I want to write a concurrent program that actually works correctly, why would I choose your language?

3

u/Tasty_Replacement_29 Bau 17h ago edited 16h ago

Ergonomics. I'm arguing that if you want to prevent too many classes of bugs, the language becomes very hard to write, and to use. Having the language prevent data races comes with a cost, and it doesn't guarantee concurrency correctness.

Many languages allow data races: Java, C#, Go, C, C++, D, Scala, Python, OCaml, Zig. You can write concurrent programs that work correctly in those languages. Languages that don't allow data races: Rust, Swift, Erlang, Elixir, Pony, Lean. If preventing data races would be a must, then I would argue everyone would use those languages for concurrent programs. But this doesn't seem to be the case.

2

u/matthieum 16h ago
  1. Is "memory safe, but not data-race free" the right trade-off for a simple language?

Honestly, to keep the language simple, I see only two possibilities:

  1. This one.

  2. Immutable values.

The latter is even simpler, but it's a significantly different style too.

2. Implicit sharing hides the fast/slow split. Would you prefer an explicit shared marker, or is tooling enough?

shared introduces complexity at the language level, and with it ergonomics issues.

So you're trading off ergonomics issues at writing/reading time vs ergonomics issues at performance investigation time. No silver bullet.

3. Setting the shared bit is O(n). Can this be a problem?

At least it's linear...

... still, I do want to point out that the cost isn't just time, there's also a memory cost here. Whether you use a recursive approach, or an explicit stack approach, you'll need to track what's left to visit, and that could go up to O(N) too.

So, yes, it can be a problem in specific cases.

A quick hack may be to expose a shared function, allowing the user to eagerly mark an object as shared (even if it's invisible in the type system), so they can build objects to share directly as shared, and NOT pay the cost later.

5. Is a non-deterministic close() acceptable for shared objects? Alternatively I could use refcounts here, always.

I'm not quite sure I understand the question. Are you talking about explicit close on files vs finalizers?

I'd be wary of sharing file handles across threads, in general. Those file handles regularly "hide" state: cursors, buffers, etc... so that using them from multiple-threads is a recipe for failure, if not outright Undefined Behavior. A mutex if shared would avoid UB, but the race-conditions could still be... very annoying to debug.

1

u/Tasty_Replacement_29 Bau 15h ago

> Immutable values

Yes, I came to the same conclusion. I want to support them in my language as well. But they need to be really immutable, and not like in Java where you can change array values... But for my language, I want the default to be mutable.

> No silver bullet

Yes, there is a trade-off. I want the default to be "easy to use", and if performance improvement are needed, it means more work.

> Setting the shared bit is O(n)
> there's also a memory cost here

Yes. The same problem exists if you delete (drop) a large linked list. In Rust, this will panic (stack overflow) unless if drop is implemented in user code. In my language, I have implemented a stack-safe deallocation algorithm that is a hybrid. I think the same will be need to set the shared bit.

> A quick hack may be to expose a shared function

Yes, that makes sense, thanks!

>> Is a non-deterministic close() acceptable for shared objects?

So my language allows to define a close() method per type; I think many language support something like that (finalizer in Java, etc.). Yes, this is for files etc. I think it's fine if there are some limitations and performance issues in this case. For example, re-linking the object in the close method results in panic, same in in Swift, and probably other languages. (Java allows to do this.) Starting a thread, or even sharing stuff, in the close() method is probably not a good idea either. This method needs some hard limitations I guess, otherwise it will be very very tricky to get right.

> I'd be wary of sharing file handles across threads, in general

It's probably best if some types may not be shared at all... That's a good point.