最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Thread-safe array deletions - Stack Overflow

programmeradmin1浏览0评论

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 JavaScript doesn't support threads, other than a recent HTML5 feature (and that doesn't allow sharing of arrays) – Dave Commented May 4, 2013 at 16:32
  • 1 Can you show us an example where two "threads" are trying to access an array at the same time? It should be impossible with JavaScript – Bergi Commented May 4, 2013 at 16:33
  • 1 You shell not use delete on arrays – Bergi Commented May 4, 2013 at 16:37
  • @dystroy: I know it is (though some oddities), but the OP sounded like he had an actual problem with concurrency… – Bergi Commented May 4, 2013 at 16:43
  • 2 Over-thinking a problem that doesn't exist? :) – deceze Commented May 4, 2013 at 16:55
Add a comment  | 

2 Answers 2

Reset to default 14

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.

发布评论

评论列表(0)

  1. 暂无评论