Mutex with multiple processes Node.js

huangapple go评论69阅读模式
英文:

Mutex with multiple processes Nodejs

问题

我看到了这篇文章,它基本上允许使用互斥锁来避免在单个进程上运行时出现竞态条件。作者表示:

> 如果你在多个进程上运行你的应用程序(例如,使用集群模块、工作线程或像pm2这样的多进程运行器),在我们的代码中使用互斥锁不会解决跨进程的竞态条件。如果你在多个服务器上运行你的应用程序也是一样。

我相当确信,这对于运营购物中心的公司来说是一个典型的用例。人们可以同时购买,而系统可能会允许一些用户继续购买,即使没有剩余数量了。

只要在单个进程上运行,就可以避免这种情况,但当服务器上线并使用pm2时,人们如何解决多个集群的互斥锁问题?还有没有其他不使用pm2的方法?

英文:

I came across reading this article, it basically allows using mutex to avoid race conditions running on a single process. The author states that

> If you are running your application on multiple processes (for instance, by using the cluster module, worker threads or a multi-process runner like pm2) using a mutex within our code is not going to solve race conditions across processes. This is also the case if you are running your application on multiple servers.

I'm pretty sure this is a typical use case for a company running a shopping mall. People can purchase it at the same time and system might let some users still able to purchase although there were no more quantities left.

Can be prevented just running on a single process, but when the server goes on production using pm2, how do people tackle mutex-lock problem with multiple clusters? or is there another way not using pm2?

答案1

得分: 1

Mutex 用于防止多个进程同时编辑变量,否则可能导致类似文章中的竞态条件。

对于你提到的购物中心和一般用例,通常我们会将可用商品数量存储在持久性存储或数据库中,因为你希望在程序关闭后仍然保留可用商品数量。如果将值存储在变量中,那么在程序关闭后会被删除。持久性存储和数据库都有自己的锁定机制,可以处理多个进程同时访问值的情况。

还有其他处理你的示例的技术。

英文:

Mutex is use for prevent multiple process to edit variable at the same time which will cause race condition like in the article.

For your example about shopping mall and general usecase, we normally store number of available item in persistent storage or database because you want to keep number of available item even after the program is closed. If you store value in variable, everything will delete after program is closed. Persistent storage and database have their own locking mechanism which can handle multiple process access value at the same time.

There are also other techniques to handle your example.

huangapple
  • 本文由 发表于 2023年6月5日 01:29:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76401619.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定