What is and how does the "Atomics" object work in Javascript?

Asked

Viewed 37 times

1

According to the documentation:

The object Atomics provides atomic operations as static methods. They are used with objects SharedArrayBuffer.

But it doesn’t seem clear to me. I would like to know what this object is and how it works Atomics in Javascript. What is its purpose and when it should be used?

1 answer

1


Opa Luiz,

First to understand what Javascript’s Atomics does we need to understand what atomic operations are in computation and what they exist for.

Competition, Parallelism and race condition

First thing to understand atomic operations, we need to understand that our operating system works by operating multiple threads simultaneously, and sometimes a simple people’s line of code like:

x = x + 5;

can be stopped in the middle of its processing and turned to be processed after.

It turns out that you imagine that two distinct threads access this resource x, if a thread A is running this operation, and it’s paused, then a thread b changes the value of x in the middle of the process, the thread a will run this operation in the wrong way.

Operações Atomic

That being said, some programming languages have atomic operations, which are indivisible operations, to which the operating system will not be able to "pause" and thread in the middle of these operations.

Javascript’s Atomics method

In 2017 Javascript introduced the Shared Memory and the Atomics, and so for example you can use the SharedArrayBuffer to share data in this shared memory between your thread principal do JS and threads de web worker for example, to which if you access the same resource simultaneously, you can generate the running condition mentioned above.

Therefore the Atomics brings a number of methods you can use to treat this race condition, making these shared resource operations atomic, blocking access from another thread while a thread accesses this resource.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.