llvm-mos-sdk icon indicating copy to clipboard operation
llvm-mos-sdk copied to clipboard

Implement <atomic>

Open mysterymath opened this issue 2 years ago • 2 comments

Since we define there to be exactly one main thread, we can have a fairly trivial implementation. Special care should be given to whether char is defined to be lock-free; lock free atomics gain additional semantics WRT signal handlers. The others should not be lock-free, since they're not actually atomic.

mysterymath avatar Mar 03 '22 05:03 mysterymath

What is the intended abstract machine like? A single-processor system with only a main thread and some interrupt handler routines? In such case, it would seem that some special cases, such as std::atomic<char>::fetch_add(1) or std::atomic<char>::fetch_sub(1) where the return value is not needed, could be translated into inc or dec. In other cases, we would seem to need sei and cli wrapping around normal instructions (if we ignore race conditions with NMI handlers). Technically, some special cases, such as

inline bool f(std::atomic<char> &a) { return a.fetch_sub(1)==1; }

could be translated into dec and checking the Z flag. The N and V flags could be utilized in some cases as well.

I only now realized that std::atomic lacks any bit-shifting operations, which along with inc and dec are the only read-modify-write operations that the NMOS 6502 implemented. Special cases of the fetch_or() and fetch_and() could be translated into the 65C02 8-bit trb or tsb instructions, somewhat similar to the 80386 1-bit BTR and BTS.

I assume that supporting the C++20 std::atomic::wait() along with notify_one() and notify_all() is out of the question, because it would require implementing a wait queue as well as a thread scheduler.

dr-m avatar Jul 17 '22 13:07 dr-m

It's not common, but also not unheard of, to build a little multithreaded rtos on the 6502 using timer interrupts and the like.

I'd expect that there'd only be a couple true wait-free atomics on the 6502; just the ones you mentioned. TSB and TRB should allow building a wait free book, but honestly I haven't thought too much about the details yet.

Most of the library would then basically reduce down to lock libcalls that could be satisfied by anyone writing a threading library. Aside from atomic on CNOS, this likely wouldn't be a very good library, so it's more a matter of standards compliance than anything else.

mysterymath avatar Jul 17 '22 16:07 mysterymath