473,399 Members | 3,401 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Is Mutex Owned?

Given an object of type Mutex, what method or property should be called to
determine if it is currently owned?

I could call WaitOne(0,false) -- and if the return value is false, I could
deduce that the Mutex is already owned... but this has the unwanted side
effect of seizing ownership of the Mutex in the case where the Mutex is NOT
already owned.

I'm looking for something like an "IsOwned" property.

Sep 26 '07 #1
11 3661
On Sep 26, 8:03 am, "Lamont Sanford" <yaBigDu...@sanford.sonwrote:
Given an object of type Mutex, what method or property should be called to
determine if it is currently owned?

I could call WaitOne(0,false) -- and if the return value is false, I could
deduce that the Mutex is already owned... but this has the unwanted side
effect of seizing ownership of the Mutex in the case where the Mutex is NOT
already owned.

I'm looking for something like an "IsOwned" property.
Yes, that'd be nice. I use Mutex.OpenExisting (added in .NET 2.0):

public static bool IsMutexOwned(string key)
{
try
{
Mutex.OpenExisting(key);
return true;
}
catch (WaitHandleCannotBeOpenedException)
{
return false;
}
}

Michael

Sep 26 '07 #2
On Sep 26, 12:03 pm, "Lamont Sanford" <yaBigDu...@sanford.sonwrote:
Given an object of type Mutex, what method or property should be called to
determine if it is currently owned?

I could call WaitOne(0,false) -- and if the return value is false, I could
deduce that the Mutex is already owned... but this has the unwanted side
effect of seizing ownership of the Mutex in the case where the Mutex is NOT
already owned.

I'm looking for something like an "IsOwned" property.
I don't think there is one aside from what you just said i.e. check to
see if you grabbed the lock and if so release it immediately. The
complement of the return value indicates whether something else had
the lock. But if you aren't accessing a critical section, why do you
want to know the status of the mutex? Or are you trying to use a
named mutex to prevent multiple copies of your app from running? If
that's the case, there are better ways of doing that...

Sep 26 '07 #3
>
Yes, that'd be nice. I use Mutex.OpenExisting (added in .NET 2.0):
Interesting technique. Thanks for the tip.
Sep 26 '07 #4
having IsOwned property will not do you much because it may fail after the
check :

if (Mutex.IsOwned("") == false)
{
// if you try to get the mutex here you can fail.
}

This is a common problem, same goes with sockets.IsConnected;

<mp*******@gmail.comwrote in message
news:11**********************@19g2000hsx.googlegro ups.com...
On Sep 26, 8:03 am, "Lamont Sanford" <yaBigDu...@sanford.sonwrote:
>Given an object of type Mutex, what method or property should be called
to
determine if it is currently owned?

I could call WaitOne(0,false) -- and if the return value is false, I
could
deduce that the Mutex is already owned... but this has the unwanted side
effect of seizing ownership of the Mutex in the case where the Mutex is
NOT
already owned.

I'm looking for something like an "IsOwned" property.

Yes, that'd be nice. I use Mutex.OpenExisting (added in .NET 2.0):

public static bool IsMutexOwned(string key)
{
try
{
Mutex.OpenExisting(key);
return true;
}
catch (WaitHandleCannotBeOpenedException)
{
return false;
}
}

Michael
Sep 26 '07 #5
On Sep 26, 8:36 am, "Ido Samuelson" <ido.samuel...@gmail.comwrote:
having IsOwned property will not do you much because it may fail after the
check :

if (Mutex.IsOwned("") == false)
{
// if you try to get the mutex here you can fail.

}
.... but it's helpful if you don't need to own the mutex. As an
example, here's how I use my IsOwned() method in a launcher/updater
tool:

if mutex is owned
switch to process owning that mutex
else
modify files used by processes that could own the mutex
launch the process (and only I launch the process)

So while there might be a race condition, the chance is vanishingly
small, as the launcher itself uses a mutex to assure a single instance
of itself.

Michael
Sep 26 '07 #6
but you can then view at the different way :-)

if (Mutex.IsOwned(""))
{
/// move to different process
}

this can still crash since the mutex can be free during.
Since you intercorporate with out of process , you should assume it can fail
always - basis for risk analysis.

<mp*******@gmail.comwrote in message
news:11*********************@d55g2000hsg.googlegro ups.com...
On Sep 26, 8:36 am, "Ido Samuelson" <ido.samuel...@gmail.comwrote:
>having IsOwned property will not do you much because it may fail after
the
check :

if (Mutex.IsOwned("") == false)
{
// if you try to get the mutex here you can fail.

}

... but it's helpful if you don't need to own the mutex. As an
example, here's how I use my IsOwned() method in a launcher/updater
tool:

if mutex is owned
switch to process owning that mutex
else
modify files used by processes that could own the mutex
launch the process (and only I launch the process)

So while there might be a race condition, the chance is vanishingly
small, as the launcher itself uses a mutex to assure a single instance
of itself.

Michael

Sep 26 '07 #7
Peter Duniho wrote:
[...]
"Vanishingly small" is not a good way to design code. You could make
the code correct, rather than relying on rarity of situations to prevent
bad behavior.
And by "could", I meant "should". :)
Sep 26 '07 #8
On Sep 26, 9:25 am, "Ido Samuelson" <ido.samuel...@gmail.comwrote:
but you can then view at the different way :-)

if (Mutex.IsOwned(""))
{
/// move to different process

}

this can still crash since the mutex can be free during.
Since you intercorporate with out of process , you should assume it can fail
always - basis for risk analysis.
Doesn't matter. If the mutex is freed between the check and the
launch, the app is simply launched again. The launched process then
checks its own mutex and either continues launching or defers to the
existing process. (I should say that I'm using Process.Start() here)

In this way, the semantics of an IsMutexOwned() method is useful to
me. It's dangerous in some contexts, though, and we agree, on your
underlying point. Analyse your code for possible failures modes.

Michael

Sep 26 '07 #9
Or are you trying to use a named mutex to prevent multiple copies of your
app from running? If that's the case, there are better ways of doing
that...
Actually, yeah, that's what I was using it for... but consider this:

I'm attempting to own the Mutex in the context of a fairly large try{}
block. The finally{} handler performs a ReleaseMutex() and Close()... but
ReleaseMutex() should only be called if the Mutex is actually owned by the
executing process. I need to know whether the Mutex is owned (by my
currently executing process) before attempting to release it.

I could always set and check my own internal bool variable ('isMutexOwned'),
and that works just fine, but it just struck me as odd that the Mutex didn't
provide an IsOwned property -- similar to the IsReaderLockHeld property of
the ReaderWriter lock.
Sep 26 '07 #10
Lamont Sanford wrote:
>Or are you trying to use a named mutex to prevent multiple copies of your
app from running? If that's the case, there are better ways of doing
that...

Actually, yeah, that's what I was using it for... but consider this:

I'm attempting to own the Mutex in the context of a fairly large try{}
block. The finally{} handler performs a ReleaseMutex() and Close()... but
ReleaseMutex() should only be called if the Mutex is actually owned by the
executing process. I need to know whether the Mutex is owned (by my
currently executing process) before attempting to release it.
A mutex is owned by a thread, not a process. Using a named mutex you
can accomplish inter-process synchronization, but it's still a specific
thread within the process that owns the mutex.

This may or may not be relevant in your own case (e.g. it wouldn't
matter for a single-threaded application), but it's worth pointing out IMHO.
I could always set and check my own internal bool variable ('isMutexOwned'),
and that works just fine, but it just struck me as odd that the Mutex didn't
provide an IsOwned property -- similar to the IsReaderLockHeld property of
the ReaderWriter lock.
For what it's worth, the property you seem to want is significantly
different from the property that most (if not all) of us assumed you
wanted. That is, you seem to be asking for a way to know if the
executing thread is actually the one holding the mutex. This is a lot
different from simply wanting to know if the mutex is being held by
_any_ thread (in-process or otherwise).

Now, all that said...it seems to me that if you don't want to keep a
local variable to track whether you've successfully acquired the mutex
or not, you should simply acquire the mutex _before_ the
try/catch/finally block of code. IMHO, code protected by a mutex (or
other synchronization object, for that matter) should generally look
like this:

if (/* successfully acquire object */)
{
/* Do some work */

/* release acquired object */
}

In other words, the object "protects" a section of code, and at the very
end of that section, you release the object. So, instead of this:

bool fHaveObject = false;

try
{
if (/* successfully acquire object */
{
fHaveObject = true;

/* Do some work */
}
}
finally
{
if (fHaveObject)
{
/* release acquired object */
}
}

You should have something like this:

if (/* successfully acquire object */)
{
try
{
/* Do some work */
}
finally
{
/* release acquired object */
}
}

You may have to nest try/finally blocks to use that pattern (depending
on what else the code is doing), but IMHO if you have a block of code so
large that's a problem, you probably are dealing with some code that
ought to be broken into multiple methods anyway.

If that specific pattern doesn't work in your case, and you would like
something different than what you actually have, you might consider
posting the block of code that's giving you trouble. I'll bet someone
will have an idea of a different way to do it. :)

Pete
Sep 26 '07 #11
Thanks, Pete. The explanation was very helpful.

I'm learning some great stuff from this newsgroup.
Sep 26 '07 #12

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Srijit Kumar Bhadra | last post by:
Hello, Here is some sample code with pywin32 build 203 and ctypes 0.9.6. Best regards, /Srijit File: SharedMemCreate_Mutex_win32all.py # This application should be used with...
0
by: Stuart M. Ray | last post by:
Hi All, The first parameter on the System.Threading.Mutex constructor is a Boolean called initiallyOwned that, according to the documentation, will give the calling thread ownership if it is...
1
by: Rocky | last post by:
I am using the following piece of code to ensure that my application only runs once, however I have a few questions about it. static Mutex m_Mutex; << in c# I assume that when the methods are...
16
by: Ed Sutton | last post by:
I use a mutex to disallow starting a second application instance. This did not work in a release build until I made it static member of my MainForm class. In a debug build, first instance got...
4
by: jcrouse | last post by:
I have searched this board for an example and also read Cor's link to the Google thread. I have an application with a startup module called mStartup. My application, after compiled is called...
8
by: Chris | last post by:
I have an app that is run periodically using Winsows Scheduled Tasks. Occasionally, the app will still be running by the time the scheduled task rolls around again. I don't want the task...
4
by: m_palmer45 | last post by:
Hi, I was looking at the code in the standard lib's mutex.py, which is used for queuing function calls. Here is how it lets you acquire a lock: def testandset(self): """Atomic test-and-set --...
3
by: NaeiKinDus | last post by:
Hello, i'm trying to program a thread that would be locked (by a mutex) and that would only be unlocked once that a function (generating data) is done. The purpose is to generate data, and unlock...
11
by: Lamont Sanford | last post by:
Given an object of type Mutex, what method or property should be called to determine if it is currently owned? I could call WaitOne(0,false) -- and if the return value is false, I could deduce...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.