p10m
asked on
Why Semaphore not working ?
Hi,
I have written a simple Dialog Based application in VC++. I have added one class to it named CMyResource.
There are 8 Instances of my resource and I want to allow only 4 at a time and concurrently . I believe this suggests
use of semaphores. So In my main dialog class
I have created instance of CSemaphore and Used
CSingleLock to point to it. Initial count for semaphore
Have kept to 4 ie
CSemaphore mySemaphore(1,4); and
CSingleLock myLock(&mySemaphore);
I have used Afxbegin thread to create threads for all 8
instances But somehow it is not working. All 8 instances
are getting simultaneous access.
I checked the condition by
if(myLock.lock())
{
//Access resource
}
else
{
//Report Access Denied
}
Can anybody tell me why is it not working ?
Any help appreciated..
Thanks
p10m
I have written a simple Dialog Based application in VC++. I have added one class to it named CMyResource.
There are 8 Instances of my resource and I want to allow only 4 at a time and concurrently . I believe this suggests
use of semaphores. So In my main dialog class
I have created instance of CSemaphore and Used
CSingleLock to point to it. Initial count for semaphore
Have kept to 4 ie
CSemaphore mySemaphore(1,4); and
CSingleLock myLock(&mySemaphore);
I have used Afxbegin thread to create threads for all 8
instances But somehow it is not working. All 8 instances
are getting simultaneous access.
I checked the condition by
if(myLock.lock())
{
//Access resource
}
else
{
//Report Access Denied
}
Can anybody tell me why is it not working ?
Any help appreciated..
Thanks
p10m
Additional explanation:
myLock.lock() - returns only TRUE, because it's parameter DWORD dwTimeOut has default value INFINITE, that means - wait until the object is signaled before returning.
myLock.lock() - returns only TRUE, because it's parameter DWORD dwTimeOut has default value INFINITE, that means - wait until the object is signaled before returning.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Don't forget that the mutex object needs to be either a global variable or a static member of the class ... otherwise, each instance of the class will have it's own copy!
-- Dan
-- Dan
This line gets access to semaphore immidiately, if it is free. If not, it waits untill semaphore is released. else branch is never called. All your threads get access to resource, but not simultenously.
To see that it really works, add MessageBox call to each thread. MessageBox stops thread and waits for OK click. All this time resource is locked. If semaphore works as expected, you will not see more than 4 message boxes simultemously.
By the way, I think you should create the semafore with initial count 0:
CSemaphore mySemaphore(0,4);