使用已命名的互斥体作为指示符是一个好主意吗? [英] Is it a good idea to use the existence of a named mutex as an indicator?

查看:100
本文介绍了使用已命名的互斥体作为指示符是一个好主意吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个命名的互斥锁来检测我的应用程序的其他实例并相应地退出,并发现有两种方法可以做到这一点:

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. 创建互斥锁;忽略该指示是否已经存在;尝试获取它;利用获取成功/失败的事实.
  2. 创建互斥锁;使用指示是否已经存在.

我无法决定是否要获取互斥锁(并在退出时释放).一方面,即使没有任何区别也能获得和释放,这看起来像是在耕种货物,但另一方面,互斥对象的存在听起来像是其实际预期功能的副作用.

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.

那么,我应该执行#1或#2来检测应用程序是否已经在运行吗?

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

推荐答案

该互斥体已经存在的指示足以让您知道至少还有一个其他进程.不需要为此使用互斥量.

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.

这样,如果实例2想与实例1对话,它知道实例1一旦能够至少进入互斥体一次,就准备好侦听.如果您按照最初发出的信号创建互斥体,以确保创建者成为第一所有者,那么这样做会更好.

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.

这篇关于使用已命名的互斥体作为指示符是一个好主意吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆