CSingleLock锁定问题 [英] CSingleLock Locking problem

查看:455
本文介绍了CSingleLock锁定问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我有两个工作线程,一个是读取COM端口,另一个是写入COM端口.我是CMutex和CSingleLock,用于线程同步.

Hi guys , i have two worker threads one is to read COM port and another is for write to COM port.I am CMutex and CSingleLock for thread Synchronization.

Class CMyApp : public CWinApp
{
public:
  CMyApp();

  ....

  CWinThread *pReadingThread, *pWritingThread;
  CMutex m_mutex;
  CSingleLock m_Lock;
};

///////////////CMyApp.Cpp

CMyApp::CMyApp():m_Lock(&m_mutex)
{
  ....
  m_mutex.m_hObject = CreateMutex(NULL, TRUE, _T("MyMutex"));
}

void CMainFrame::OnStart()
{
  theApp.m_pReadingThread = AfxBeginThread(Reading, &theApp);
  theApp.m_WritingThread = AfxBeginThread(Writin, &theApp);
}

//////////////I have two global methods

UINT Reading(LPVOID lpParam)//lpParam is CMyApp pointer
{
  CMyApp* pApp = (CMyApp*)lpParam;
   while(pApp->m_Lock.Lock())    // Here Lock waits infinitely
  {
    reading process....
    pApp->m_Lock.UnLock();
  }
}

UINT Writing(LPVOID lpParam)
{
   CMyApp* pApp = (CMyApp*)lpParam;
   while(pApp->m_Lock.Lock())   // Here Lock waits infinitely
   {
     writing process....
     pApp->m_Lock.UnLock();
   }
}



CSingleLock无限等待,即使一次也不会被锁定.
如果您知道如何指导我,我不知道怎么了

在此先感谢
ganesh_IT



CSingleLock waits infinitely it is never locked even a single time.
I dont know whats wrong if you know guide me

Thanks in advance
ganesh_IT

推荐答案

您的同步设计错误:

Your synchronization design is wrong:

// suppose this is the first thread locking the mutex
while(pApp->m_Lock.Lock())    
{
  // process data, i.e. some CPU cycles
  // (1) here the mutex is locked by this thread
  pApp->m_Lock.UnLock();
  // no CPU cycles here
  // (2) here the mutex is unlocked, but it will be locked again, by this thread, at the very next machine cycle.
}




如您在上述说明中所看到的,第一个能够锁定互斥锁的线程将从不给另一线程一个机会(或者,如果您愿意的话,它也提供了0概率的机会)来锁定自身.互斥锁.




As you may see in the above remarks, the first thread able to lock the mutex will never give the other thread a chance (or it gives a 0-probability chance, if you prefer) of locking itself the mutex.


您需要使用waitforsingleobject或waitformultiple对象功能.
you need to use the waitforsingleobject or waitformultiple objects functions.


这篇关于CSingleLock锁定问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆