Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

What is a mutex?

2 views
Skip to first unread message

Jim Carlock

unread,
Aug 17, 2003, 2:29:32 PM8/17/03
to
I've noticed references to a mutex when it comes to talking about
creating single instance applications. What exactly is a mutex?

--
Jim Carlock
http://www.microcosmotalk.com
Feel free to post back to the newsgroup!

alpine

unread,
Aug 17, 2003, 4:16:41 PM8/17/03
to
On Sun, 17 Aug 2003 14:29:32 -0400, "Jim Carlock"
<an...@localhost.com> wrote:

>I've noticed references to a mutex when it comes to talking about
>creating single instance applications. What exactly is a mutex?


Have a look at the following (watch for wordwrap).....

[http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dllproc/base/synchronization.asp?frame=true]


HTH,
Bryan
____________________________________________________________
New Vision Software "When the going gets weird,"
Bryan Stafford "the weird turn pro."
alpine_don'tsen...@mvps.org Hunter S. Thompson -
Microsoft MVP-Visual Basic Fear and Loathing in LasVegas

Jim Carlock

unread,
Aug 17, 2003, 6:02:16 PM8/17/03
to
Mutex really sounds like a synonym for thread. And it might
be fully defined as "a thread of execution, identified by a unique
handle".

Is that correct?

--
Jim Carlock
http://www.microcosmotalk.com
Feel free to post back to the newsgroup!


"alpine" <alpine_don'tsen...@mvps.org> wrote in message
news:ujovjvofvaskhfvdj...@4ax.com...

Tom Esh

unread,
Aug 17, 2003, 6:35:19 PM8/17/03
to
On Sun, 17 Aug 2003 18:02:16 -0400, "Jim Carlock"
<an...@localhost.com> wrote:

>Mutex really sounds like a synonym for thread. And it might
>be fully defined as "a thread of execution, identified by a unique
>handle".
>
>Is that correct?

Nope, though a common use for them is to synchronize threads in a
multi-threaded app. It's essentially just a system object that can be
owned by only one thread at any given time, hence it's usefulness in
instance control.


-Tom
MVP - Visual Basic
(please post replies to the newsgroup)

Tom Esh

unread,
Aug 17, 2003, 7:03:22 PM8/17/03
to
On Sun, 17 Aug 2003 18:02:16 -0400, "Jim Carlock"
<an...@localhost.com> wrote:

>Mutex really sounds like a synonym for thread. And it might
>be fully defined as "a thread of execution, identified by a unique
>handle".
>
>Is that correct?

If it helps, here's a tiny class that uses a mutex to prevent multiple
app instances.

'=== class clMutexPI ===
Private Declare Function ReleaseMutex Lib "kernel32" _
(ByVal hMutex As Long) As Long
Private Declare Function WaitForSingleObject Lib "kernel32" _
(ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare Function CreateMutex Lib "kernel32" _
Alias "CreateMutexA" _
(ByVal lpMutexAttributes As Long, _
ByVal bInitialOwner As Long, ByVal lpName As String) As Long
Private Declare Function CloseHandle Lib "kernel32" _
(ByVal hObject As Long) As Long
Private Const WAIT_FAILED = -1&
Private Const WAIT_OBJECT_0 = 0
Private Const WAIT_TIMEOUT = &H102&

Dim m_hMutex As Long

Public Property Get PrevInst() As Boolean
PrevInst = (m_hMutex = 0&)
End Property

Private Sub Class_Initialize()
Dim lRet As Long, hM As Long

hM = CreateMutex(0&, 0&, App.Title & "Instance")
If hM <> 0& Then
lRet = WaitForSingleObject(hM, 1&) 'request ownership
If (lRet <> WAIT_TIMEOUT) And (lRet <> WAIT_FAILED) Then 'got it
m_hMutex = hM
End If
End If
End Sub

Private Sub Class_Terminate()
If m_hMutex <> 0& Then
ReleaseMutex m_hMutex
CloseHandle m_hMutex
End If
End Sub

'==== usage - bas module ========================
The idea is to create an instance of the class immediately on app
startup and keep it until the app terminates. Typically that would be
done in the same bas module as Sub Main.
Ex:

'since it's in a bas module, the PI instance has app lifetime...
Dim PI as clMutexPI

Sub Main()
Set PI = New clMutexPI
If Not PI.PrevInst Then
'..do app startup...
End If
End Sub

Jim Carlock

unread,
Aug 17, 2003, 8:05:31 PM8/17/03
to
Is there a metaphor around that might represent what a mutex
is? Right now, I see it as being stuck in a list of owners... like a
rental car. Each owner gets to use it for an alotted amount of
time and while it is possible for a rented car to be in the hands
of two renters at any given instance, only one is the driver (hence
termed owner or responsible party).

So I'm thinking its similar to a renter in a list of renters. Or to
stick with the term owner and owners, it can be described as
a timeshare. The alotted owner gets it for a certain amount of
time. And if the owner wants to grab more time, it has to be
stuck in the list of awaiting owners who are waiting to use their
time up.

I'm working on creating a single instance because the current
functions I'm using do NOT work if the program is renamed
or copied and started from another folder.

I think it's because I have it all enclosed in an:

If App.PrevInstance Then

So I'm looking to get rid of the App.PrevInstance.

And I've got a:

hw = FindWindowByString(lpClassName, lpWindowName)

So right at this moment I have to figure out what gets put into
hw&.

Declare Function FindWindowByString _
Lib "user32.dll" Alias "FindWindowA" _
(ByVal lpClassName$, ByVal lpWindowName$) As Long

This looks like it should work. I'm calling it within Main() to
catch the App before it gets loaded. It looks like it can return
a NULL value though. So I might have to implement
something to accomodate the NULL instead of forcing it into
a string.

--
Jim Carlock
http://www.microcosmotalk.com
Feel free to post back to the newsgroup!


"Tom Esh" <tjeshGi...@earthlink.net> wrote in message
news:ed00kvgfavjquj80s...@4ax.com...

Galen Somerville

unread,
Aug 17, 2003, 9:40:16 PM8/17/03
to
mutex

A mutual exclusion object that allows multiple threads to synchronise access
to a shared resource. A mutex has two states: locked and unlocked.
Once a mutex has been locked by a thread, other threads attempting to lock
it will block.
When the locking thread unlocks (releases) the mutex, one of the blocked
threads will
acquire (lock) it and proceed.

If multiple threads or tasks are blocked on a locked mutex object,
the one to take it and proceed when it becomes available is determined by
some type
of scheduling algorithm. For example, in a priority based system, the
highest
priority blocked task will acquire the mutex and proceed.
Another common set-up is put blocked tasks on a first-in-first-out queue.

From Google

Galen

"Jim Carlock" <an...@localhost.com> wrote in message
news:eYCXyxRZ...@TK2MSFTNGP12.phx.gbl...

Peter Young

unread,
Aug 17, 2003, 9:55:18 PM8/17/03
to
"Jim Carlock" <an...@localhost.com> wrote in message
news:eYCXyxRZ...@TK2MSFTNGP12.phx.gbl...
> Is there a metaphor around that might represent what a mutex
> is?

The term mutex comes from MUTually EXclusive. Think of it as a unique name
that can have only one owner.


> I think it's because I have it all enclosed in an:
>
> If App.PrevInstance Then
>
> So I'm looking to get rid of the App.PrevInstance.

Why?


> And I've got a:
>
> hw = FindWindowByString(lpClassName, lpWindowName)
>
> So right at this moment I have to figure out what gets put into
> hw&.
>
> Declare Function FindWindowByString _
> Lib "user32.dll" Alias "FindWindowA" _
> (ByVal lpClassName$, ByVal lpWindowName$) As Long
>
> This looks like it should work. I'm calling it within Main() to
> catch the App before it gets loaded. It looks like it can return
> a NULL value though. So I might have to implement
> something to accomodate the NULL instead of forcing it into
> a string.

Take a look at PrevInst.zip on this page for the details, including how to
send data to the previous instance:
http://www.mvps.org/vb/samples.htm

-Pete


Tom Esh

unread,
Aug 17, 2003, 10:06:04 PM8/17/03
to
On Sun, 17 Aug 2003 20:05:31 -0400, "Jim Carlock"
<an...@localhost.com> wrote:

>Is there a metaphor around that might represent what a mutex
>is? Right now, I see it as being stuck in a list of owners... like a
>rental car. Each owner gets to use it for an alotted amount of
>time and while it is possible for a rented car to be in the hands
>of two renters at any given instance, only one is the driver (hence
>termed owner or responsible party).
>
>So I'm thinking its similar to a renter in a list of renters. Or to
>stick with the term owner and owners, it can be described as
>a timeshare. The alotted owner gets it for a certain amount of
>time. And if the owner wants to grab more time, it has to be
>stuck in the list of awaiting owners who are waiting to use their
>time up.

More like any renter / thread can request ownership and keep it as
long as it wants. The OS imposes no time limit or sharing requirement.
The only time factor is how long a thread wants to wait for ownership
before giving up if another thread owns the mutex. That's done via the
timeout arg in WaitForSingleObject, but in a single-threaded app and
for the purposes of maintaining a single app instance there's no
reason to wait at all.


>I'm working on creating a single instance because the current
>functions I'm using do NOT work if the program is renamed
>or copied and started from another folder.
>
>I think it's because I have it all enclosed in an:
>
>If App.PrevInstance Then
>
>So I'm looking to get rid of the App.PrevInstance.
>
>And I've got a:
>
>hw = FindWindowByString(lpClassName, lpWindowName)
>
>So right at this moment I have to figure out what gets put into
>hw&.
>
>Declare Function FindWindowByString _
> Lib "user32.dll" Alias "FindWindowA" _
> (ByVal lpClassName$, ByVal lpWindowName$) As Long
>
>This looks like it should work. I'm calling it within Main() to
>catch the App before it gets loaded. It looks like it can return
>a NULL value though. So I might have to implement
>something to accomodate the NULL instead of forcing it into
>a string.

You can think of the PrevInst property of the mutex class I provided
earlier as simply a more robust version of App.PrevInstance - one that
won't get fooled by an exe re-name, different startup directory, or
two or more rapid succession launches. Using that class, you could
order your startup tests as follows:

'=== bas module ===

'PI is a module-level var in the bas module.
'That way if this app instance gets ownership of the mutex,
'it won't go out of scope and release the mutex until this
'app instance terminates. That way any subsequent instance will see us
as a previous instance.
Dim PI As clMutexPI

Sub Main()
Set PI = New clMutexPI
If Not PI.PrevInst Then

'Got ownership - we're the only instance.
'...do the normal startup stuff...
Else
'Mutex ownership request refused, meaning
'the mutex is owned by another (previous) instance.
'The only reason to use FindWindow here would be to obtain
'a hwnd of the previous instance so we can communicate with it.
'via SendMessage for example.
'Since we already know that a prev instance is running, it's
'very unlikely that FindWindow would fail here unless the args
'are wrong.
'If there's no reason to communicate with the previous instance,
'do nothing and this one dies immediately.
End If
End Sub

Ben Taylor

unread,
Aug 18, 2003, 3:48:45 AM8/18/03
to
Since the only real information you got from most of these
replies seems to be that "it's something to do with
threads", you really want to be just reading the google
definition Galen Somerville posted and then starting to
use mutexes to gain a more 'on-the-job' perspective of how
mutexes work.
A mutex can be used by two different processes, whereby
they have to have a name - hence their frequent use to
prevent two different instances of an application running
at once.

>.
>

Tony Proctor

unread,
Aug 18, 2003, 5:03:30 AM8/18/03
to
This is an important point Ben has raised. Mutexes provide "mutual
exclusion" for resources shared by multiple threads, and/or multiple
processes. In a threads-only scenario, "critical sections" provide a much
more efficient mechanism for mutual exclusion. Unfortunately, because of
their dependence on shared memory, it makes them less than useful where VB
threads, using ActiveX EXEs, are involved. The VB run-time environment
deliberately makes it difficult to share data in a multi-threaded
application.

Tony Proctor

"Ben Taylor" <ben_ta...@yahoo.co.uk> wrote in message
news:05b601c3655d$26db0e40$a401...@phx.gbl...

Jeff Johnson [MVP: VB]

unread,
Aug 18, 2003, 9:01:01 AM8/18/03
to

"Jim Carlock" <an...@localhost.com> wrote in message
news:eYCXyxRZ...@TK2MSFTNGP12.phx.gbl...

> Is there a metaphor around that might represent what a mutex
> is?

A book. Ignoring things like looking over someone's shoulder, only one
person can be reading a book at any given time. For someone else to read it
the book has to be passed to him.


Andrew Faust

unread,
Aug 18, 2003, 12:27:59 PM8/18/03
to

"Jim Carlock" <an...@localhost.com> wrote in message
news:eYCXyxRZ...@TK2MSFTNGP12.phx.gbl...
> Is there a metaphor around that might represent what a mutex
> is?

Suppose you have a door that requires a key to enter. Now everyone
who wants to enter that door must have the key in their posession
to enter the door. The catch is that there is only one key. Thus
if someone wants to enter the door, they have to wait for the person
who has the key to give it to them, before they can.

Here's the fun part. If the person with the key never gives it up to someone
else who is waiting for it then it means no one else gets to enter the door
thus causing deadlock.

Andrew Faust


Jim Carlock

unread,
Aug 18, 2003, 7:13:23 PM8/18/03
to
"Andrew Faust" <afa...@aradyme.com.REMOVE> wrote:
> > Is there a metaphor around that might represent what a mutex
> > is?
>
> Suppose you have a door that requires a key to enter. Now everyone
> who wants to enter that door must have the key in their posession
> to enter the door. The catch is that there is only one key. Thus
> if someone wants to enter the door, they have to wait for the person
> who has the key to give it to them, before they can.
>
> Here's the fun part. If the person with the key never gives it up to
someone
> else who is waiting for it then it means no one else gets to enter the
door
> thus causing deadlock.
>
> Andrew Faust

I was thinking of a key but duplicate keys kept popping into my
head. But now that you've posted it, I don't have to worry about
posting the duplicate key issue as you've already taken it into
account.

However, I can't help it... like the guy in Ghost Busters that
thought of the StayPuft Marshmellow man... Sorry Andrew!!! It
popped in my head!!! Who would have thought of a key, when
there's always a set of flimsy little dinky harmless lockpicks?!?!?
Or worse yet, a coat hanger!

Thanks to everyone!

I owe Tom something. I'll let Tom decide what it should be.

0 new messages