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?
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?
Share Improve this question asked May 4, 2013 at 16:31 dmkcdmkc 1,1811 gold badge15 silver badges22 bronze badges 5 |2 Answers
Reset to default 14Regarding 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.
delete
on arrays – Bergi Commented May 4, 2013 at 16:37