Re: help w/ mutex
From: Tom Stewart (tastewar_at_newsgroups.nospam)
Date: 04/30/04
- Next message: AMcDŽ: "DLL functions access"
- Previous message: lallous: "help w/ mutex"
- In reply to: lallous: "help w/ mutex"
- Next in thread: lallous: "Re: help w/ mutex"
- Reply: lallous: "Re: help w/ mutex"
- Messages sorted by: [ date ] [ thread ]
Date: Fri, 30 Apr 2004 09:25:35 -0400
Not sure I follow your code exactly, but a single thread can acquire a mutex *recursively* What they are designed to
protect against is multiple threads (possibly from multiple processes) accessing some resource at the same time. If an
individual thread acquires a mutex recursively, it must release it the same number of times that it successfully
acquired it.
If your application is single threaded, you can use global variables to track whether you "own" something or not. If
your application is multi-threaded, but you don't need cross-process protection, a CriticalSection is probably what you
need. If you have to deal with multiple processes, then a mutex is your friend. Or if you know the protected resource
will always be contended for, then the CriticalSection doesn't really offer any advantage.
--
Tom
"lallous" <lallous@lgwm.org> wrote in message news:%236ETzArLEHA.624@TK2MSFTNGP11.phx.gbl...
> Hello
>
> #include <windows.h>
> #include <stdio.h>
>
> class CClass1
> {
> private:
> HANDLE m_hProtection;
>
> class protect
> {
> private:
> HANDLE m_hMutex;
> public:
> protect(HANDLE mut);
> void acquire();
> ~protect();
> };
> public:
> CClass1();
> ~CClass1();
> void method1();
> };
>
> void CClass1::method1()
> {
> protect p1(m_hProtection);
>
> // shouldn't this lock because mutex was acquired and not released yet?
> p1.acquire();
> p1.acquire();
> }
>
> CClass1::CClass1()
> {
> m_hProtection = ::CreateMutex(NULL, FALSE, NULL);
> }
>
> CClass1::~CClass1()
> {
> ::CloseHandle(m_hProtection);
> }
>
> CClass1::protect::protect(HANDLE mut)
> {
> m_hMutex = mut;
> acquire();
> }
>
> CClass1::protect::~protect()
> {
> ::ReleaseMutex(m_hMutex);
> printf("mutex released! (GLE=%d)\n", ::GetLastError());
> }
>
> void CClass1::protect::acquire()
> {
> ::WaitForSingleObject(m_hMutex, INFINITE);
> printf("mutex acquired! (GLE=%d)\n", ::GetLastError());
> }
>
> int main()
> {
> {
> CClass1 test;
>
> test.method1();
> }
> return 0;
> }
>
> Why the code in "method1()" doesn't block after the mutex has been acquired
> the first time?
> Should'nt the call to p1.acquire() lock if it was acquired first?
>
> I thought that a mutex would be acquired if you call Waitforsingleobject and
> will be released with ReleaseMutex ...
>
> Please clarify.
>
> --
> Elias
>
>
- Next message: AMcDŽ: "DLL functions access"
- Previous message: lallous: "help w/ mutex"
- In reply to: lallous: "help w/ mutex"
- Next in thread: lallous: "Re: help w/ mutex"
- Reply: lallous: "Re: help w/ mutex"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|