Is it a good idea to use the existence of a named mutex as an indicator?

纵饮孤独 提交于 2019-12-22 08:12:13

问题


I'm using a named mutex to detect other instances of my application and exit accordingly, and found that there are two ways of doing this:

  1. Create the mutex; ignore the indication whether it already existed; try to acquire it; use the fact that acquire succeeded/failed.
  2. Create the mutex; use the indication whether it already existed.

I can't decide whether to acquire the mutex (and release on exit). On the one hand, acquiring+releasing even though it makes no known difference looks like cargo culting, but on the other hand the existence of a mutex object sounds like a side-effect of its actual intended functionality.

So, should I do #1 or #2 to detect if the app is already running?


回答1:


The indication that the mutex already existed is sufficient to let you know that there is at least one other process. There is no need to take the mutex for that.

But as long as you have the mutex, you can take it if you need to lock other instances out of some piece of code.

For instance, you can take the mutex until you get out of your initialization code. That way only one instance of your program can be in initialization at a time. If you take the mutex after opening it, the one that got the mutex first knows that no other instance is in its init code. But more importantly, the one that didn't create the mutex knows that the one that create is has finished initialization.

That way if instance 2 wants to talk to instance 1, it knows that instance 1 is ready to listen once it has been able to enter the mutex at least once. This works better if you create the mutex as initially signalled to be absolutely sure that the creator gets to be the first owner.




回答2:


I'm not sure of it but the named mutex may still exists if the program crashes and doesn't terminate properly. If so, the existence test will succeed whereas no other instance were running. Thus, I personnaly would prefer to try to acquire it ;-)




回答3:


#1 sounds the way you should go.

Create the mutex; ignore the indication whether it already existed; try to acquire it; use the fact that acquire succeeded/failed

Because your app launching code might be executed twice (on a resume or similar OS stuff), and the acquire will succeed even if the mutex is already existing as it was created by the same app id.



来源:https://stackoverflow.com/questions/2415984/is-it-a-good-idea-to-use-the-existence-of-a-named-mutex-as-an-indicator

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!