MPLLang / mpl

The MaPLe compiler for efficient and scalable parallel functional programming
Other
306 stars 18 forks source link

bugfix: update structure One to be thread-safe #175

Closed shwestrick closed 1 year ago

shwestrick commented 1 year ago

basis-library/util/one.sml defines a structure called One which is used in the basis library to optimize memory usage of a few functions, including:

This patch fixes a buggy race condition in the implementation of One. With this patch, the above functions should be safe for parallelism and concurrency.

The idea behind One is straightforward: a static buffer or mutable cell is allocated to be shared across calls. When a call is made, if the shared buffer is not in use, then the shared buffer can be claimed and used for the duration of that call, and then released.

The mechanism for claiming the buffer (inherited from MLton) was previously not thread-safe, because it was not atomic at the hardware level. For MLton, it didn't need to be. But for MPL this is no longer correct, hence the bug.

This patch switches to using an atomic compare-and-swap (CAS) to claim the buffer.