Okay, I'm trying to synchronize two threads using CEvent and
CMultilock. What I need to achieve here is that they can execute in
parallel until they reach a succession of "barriers" (borrowing a VMS
term). I am attempting this by declaring two events in each of the
threads. Each event has the same name in each thread.
The problem is that the CMultiLock Lock() function returns
successfully SOMETIMES but not always. Another thing I don't
understand is why the TRACE call to IsLocked always shows a state of
0, just after I set the event!
Any help is appreciated. The code follows:
BOOL CColCtl::OnInitDialog()
{
CDialog::OnInitDialog();
// create a multilock to synchronize startup of the two threads.
CEvent sme(0, 1, START_MAIN_EVENT), sce(0, 1, START_COLL_EVENT);
CSyncObject* events[2];
events[0] = &sme;
events[1] = ⪰
CMultiLock ml(events, 2);
// start the data collection thread
mCS.bFakeData = TRUE;
CWinThread* mCollThd = AfxBeginThread(CollectData, &mCS);
TRACE0("Collect thread started\n");
// ... other processing here ...
// wait for both threads to get to the first barrier
TRACE1("sme succ %d\n", sme.SetEvent());
TRACE1("sme state %d\n", ml.IsLocked(0));
if (ml.Lock() != -1) {
sme.ResetEvent();
TRACE0("Main thread hit barrier 1\n");
Sleep(3000); // simulated processing
TRACE0("Main thread leaving barrier 1 section\n");
} // end if Lock
else {TRACE0("Main lock failed\n");}
TRACE0("Main exit\n");
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
static UINT CollectData(void* pParam) {
CCollShare* pCS = (CCollShare*)pParam;
TRACE0("CollectData started\n");
// create a multilock to synchronize startup of the two threads.
CEvent sme(0, 1, START_MAIN_EVENT), sce(0, 1, START_COLL_EVENT);
CSyncObject* events[2];
events[0] = &sme;
events[1] = ⪰
events[2] = &sde;
CMultiLock ml(events, 2);
// other processing here
// wait for both threads to get to the first barrier
sce.SetEvent();
TRACE1("sce succ %d\n", sce.SetEvent());
TRACE1("sce state %d\n", ml.IsLocked(1));
if (ml.Lock() != -1) {
sce.ResetEvent();
TRACE0("CollectData hit barrier 1\n");
Sleep(5000); // simulated processing
TRACE0("CollectData leaving barrier 1 section\n");
} // end if Lock
else {TRACE0("CollectData lock failed\n");}
TRACE1("CollectData ended %d\n", pCS->bFakeData);
return 0;
} // end CollectData