I know one can either splice
an item out of an array, or delete it with delete
. The former approach can cause concurrency problems, e.g. if one thread is walking over the array while another has just shifted or spliced. delete
doesn't have this issue if forEach
is used on the array, since forEach
will walk over holes in the array.
However, the array can't keep growing forever and will necessitate sweeping, potentially causing the same issue as in the case of a splice. Sounds like I need locking, but I'd be amused if Javascript had any facilities for it. Any thoughts?
The C++ new and delete operators are thread safe, but this means that a thread may have to wait for a lock on these operations. Once memory is obtained for a thread, the thread_alloc memory allocator keeps that memory available for the thread so that it can be re-used without waiting for a lock.
Arrays are 'value-typed' in the effect of assignment, initialization, and argument passing — creates an independent instance with its own unique copy of its data. Immutable arrays (declared using let) are thread-safe since it is read-only. But mutable arrays are not thread-safe.
A code is called “Thread safe” if any shared data is accessed by only one thread at any given time. Notice these shared data are called critical sections in an operating system. The point is Swift collection types like Array and Dictionary are not thread-safe when declared mutable (With var keyword).
Thread safe is a concept in the context of multi-thread and it means any shared data is accessed by only one thread at any given time. If you want to write/read access to a shared resource from different threads, you should take the thread safety into consideration.
Regarding your precise question: No, you can't have concurrency problem as JavaScript isn't multithreaded. Even if you use webworkers you won't have problems as no data is shared (workers communicate by passing messages). Even in node.js your script isn't multi-threaded. There's no way that a parallel execution does anything during the execution of your function unless you use await
.
So simply use splice
, there is no need to lock the array.
Regarding concurrency problems more generally, you should be aware that, as soon as you use await
, the execution can be cut in chunks and another function can run while you're awaiting. splice
will never be cut but be careful to the logic of your algorithm on shared data when you're in an async
function.
Javascript is singlethreaded so there's no problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With