473,746 Members | 2,678 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to check if a Mutex is already locked.

I'm setting up an interface where clients must perform external
locking before calling certain commands. I do this to force them to
specify the duration the action they performed must persist before any
other threads can be allowed to perform some action.

My object exposes a Mutex which is locked via a IDisposable-Sentry
class. I want to throw an exception if certain functions are called
without this Mutex already being locked, but I cannot figure out any
way to safely check whether the mutex is already locked by the current
thread.

a.) I could attempt to lock the object with a 0 ms timeout. If this
fails, I know the client has not locked the object down externally as
required. If this succeeds, however, the mutex could have simply been
available.

b.) I could call Release on the mutex, if this throws an exception I
know the client has not locked it prior to calling the function. If it
doesn't throw, however, I have unlocked the mutex and allow the
possibility for another client to lock it down before I can re-acquire
it.

c.) I could have my IDisposable-Sentry class which performs the
locking, actually perform 2 locks, and then I could use method b to do
the locking and unlocking. This seems like it would work, but I'm
worried about the efficiency of repeated unnecessary unlocking and
locking.

d.) I could have my IDisposable-Sentry class which performs the
locking, set an internal variable indicating that it has locked the
mutex. I can check this efficiently and without introducing any subtle
effects on the mutex; but the extent to which it is actually
disassociated from the mutex bothers me.

I understand that checking whether a mutex is locked by the current
thread is a potentially abused operation, since clients could do
things like:

// Skip this operation if currently locked
if( !locked )
{
lock(); // ka-blam, long timeout inside time-sensitive code
}

But, this is simply dumb coding, and a lock(0) should have been used
instead.

I was hoping for either a .NET API function, or even a Win32 API
function that can take in the internal HANDLE and tell me whether the
current thread owns it or not.

Thankee-sai,
-ken
Nov 13 '05 #1
2 18794
Ken Durden <cr************ *@hotmail.com> wrote:
I'm setting up an interface where clients must perform external
locking before calling certain commands. I do this to force them to
specify the duration the action they performed must persist before any
other threads can be allowed to perform some action.

My object exposes a Mutex which is locked via a IDisposable-Sentry
class. I want to throw an exception if certain functions are called
without this Mutex already being locked, but I cannot figure out any
way to safely check whether the mutex is already locked by the current
thread.


Instead of a Mutex, you could expose an object reference to Enter/Exit
the Monitor of - you can then use Monitor.TryEnte r.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too
Nov 13 '05 #2
srijith.unni
1 New Member
I'm setting up an interface where clients must perform external
locking before calling certain commands. I do this to force them to
specify the duration the action they performed must persist before any
other threads can be allowed to perform some action.

b.) I could call Release on the mutex, if this throws an exception I
know the client has not locked it prior to calling the function. If it
doesn't throw, however, I have unlocked the mutex and allow the
possibility for another client to lock it down before I can re-acquire
it.

I understand that checking whether a mutex is locked by the current
thread is a potentially abused operation, since clients could do
things like:

// Skip this operation if currently locked
if( !locked )
{
lock(); // ka-blam, long timeout inside time-sensitive code
}

But, this is simply dumb coding, and a lock(0) should have been used
instead.

I was hoping for either a .NET API function, or even a Win32 API
function that can take in the internal HANDLE and tell me whether the
current thread owns it or not.

Thankee-sai,
-ken

Hi Ken,

About your second choice, where you check for the exception,
take for example, if i am using win32 API KeReleaseMutex.
It explicitly cites, that if I release a mutex, not owned, a bug check will occur.

If I were to just to call this API, within a try block, and thus handle the exception, would it avoid the bugcheck ?

Regards,
Srijith
Mar 22 '06 #3

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

Similar topics

7
20636
by: Bill Chiu | last post by:
Dear C++ Universe, I wrap pthread lock with a C++ class, and it caused crashes.. Is the below implementation a real baddy and needs serious spanking?? #include <pthread.h> class Lock { public: Lock() { pthread_mutex_init(&plock, NULL); } ~Lock() {}
193
9609
by: Michael B. | last post by:
I was just thinking about this, specifically wondering if there's any features that the C specification currently lacks, and which may be included in some future standardization. Of course, I speak only of features in the spirit of C; something like object-orientation, though a nice feature, does not belong in C. Something like being able to #define a #define would be very handy, though, e.g: #define DECLARE_FOO(bar) #define...
4
3151
by: TGOS | last post by:
I was thinking about it for a while, a mutex written in C and without disabling any interrupts. Is it possible? typdef struct mutex { unsigned int owner1; unsigend int owner2; } *mutex; void mutex_init(mutex *m) {
3
3523
by: smith4894 | last post by:
Hello, I have an application that essentially consists of two threads doing their things. One thread is a producer, and pushes bytes (of a struct) into a pipe, and another is a consumer that simply checks the pipe at regular intervals reads out the bytes. If the consumer extracts bytes and sees that it's not enough to recast to the struct, it caches it and waits for more bytes in the pipe. My question is: Do I still need to maintain...
4
1244
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 -- grab the lock if it is not set, return True if it succeeded.""" if not self.locked: self.locked = 1
6
2863
by: Jun Kusanagi | last post by:
Is there any way to solve process synchronization between more than 1 resources. I'm already trying to use Mutex.WaitAny, but I confused to execute Release method from the corresponding mutexes. Any comment will be appreciated. Best Regards,
4
1638
by: google | last post by:
Hi Guys, I'm having a bizarre problem here with mutexes. If I have the following code in a page (note that it never releases the mutex!), then load the page twice, in 2 seperate browsers, I do not get a mutex lock. Any ideas? I'm trying to get a globally accessible mutex. Is using the Application object wrong somehow?
14
9730
by: Alex K. | last post by:
Hi all I'd like to avoid starting the same c# application twice on the same computer. How do I check if it is already running? Thank you
3
5583
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 the mutex in order to activate the thread once the data is generated. I have to do it this way, i can only call the thread if the data are generated. ******************************************************** step 1: initialize the mutex
0
8974
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8800
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9508
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9350
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9285
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8229
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6772
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6060
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2765
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.