Solved

Why Semaphore not working ?

Posted on 2003-11-01
7
215 Views
Last Modified: 2013-11-20
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




 
 
0
Comment
Question by:p10m
  • 3
7 Comments
 
LVL 48

Expert Comment

by:AlexFM
ID: 9662690
myLock.lock();

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);
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 9662696
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.
0
 
LVL 48

Accepted Solution

by:
AlexFM earned 120 total points
ID: 9662886
Actually, it should be
CSemaphore mySemaphore(4, 4);

Take a look at this code:

class CSample3Dlg : public CDialog
{
    ...
    CSemaphore* m_pSemaphore;
    ...
}

BOOL CSample3Dlg::OnInitDialog()
{
    ....
    m_pSemaphore = new CSemaphore(4, 4);
    ....
}

UINT ThreadProc(LPVOID pParam)
{
    CSample3Dlg* pDlg = (CSample3Dlg*) pParam;

    CSingleLock lock(pDlg->m_pSemaphore);

    if ( lock.Lock() )
    {
        MessageBox(NULL, _T("OK"), NULL, MB_OK);
    }

    return 0;
}

void CSample3Dlg::OnButton1()
{
    for ( int i = 0; i < 8; i++ )
        AfxBeginThread(ThreadProc, this);
}

Running this code you will never see more than 4 message boxes at the same time.
0
 
LVL 49

Expert Comment

by:DanRollins
ID: 9664317
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
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Rewrite URL With Encoded Characters 6 75
Separate into files by filename 12 75
VBA "SendKeys" Syntax for Multiple Keystrokes 7 103
has77  challenge 9 71
This is to be the first in a series of articles demonstrating the development of a complete windows based application using the MFC classes.  I’ll try to keep each article focused on one (or a couple) of the tasks that one may meet.   Introductio…
Introduction: Finishing the grid – keyboard support for arrow keys to manoeuvre, entering the numbers.  The PreTranslateMessage function is to be used to intercept and respond to keyboard events. Continuing from the fourth article about sudoku. …
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
A short film showing how OnPage and Connectwise integration works.

929 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now