logoalt Hacker News

adrian_b • today at 1:57 PM • 0 replies • view on HN

On ancient single-core single-thread CPUs, threads were indeed a concept introduced by the operating system, and the use of threads was completely optional.

On modern CPUs, which have many hardware threads, the operating system and the user programs must handle at least the number of hardware threads, e.g. 32 threads on an AMD 9950X.

Implementing more threads than the hardware threads is optional, but the hardware threads must have their own states and stacks and if they exchange messages the inter-thread messages must pass through message queues located in shared memory and using algorithms that enable concurrent accesses.

Naive implementations of message queues can use locks for mutual exclusion, but better implementations exploit the fact that message queues, like also arrays, can be dynamically partitioned using atomic fetch-and-add instructions, so that many threads can access concurrently a message queue, without using either mutual exclusion or optimistic accesses (which may need retries).

It is possible to have an operating system where there exists no shared state between threads, with the exception of the shared message queues.

Because message queues can be implemented without the need for mutual exclusion, it is possible to have an operating system where mutual exclusion (i.e. locks) is not used anywhere.

Whether an operating system without shared state between threads can have a performance comparable with e.g. Linux or Windows, is an open problem.

The lack of shared state does not mean that superfluous copies are needed. The messages may contain pointers to buffers in shared memory through which the bulk of the data is transferred between threads, but those buffers always have a current owner, i.e. the receiver of the message, and no other thread attempts to access them, including the sender of the message, which has written the buffer before sending the message.