一共有两处疑惑分别位于enter和leave的结尾处。
void COptex::Enter()
{
//try to own the resource,keep waiting until another thread release it
if(TryEnter())
return; //current thread own the resource
DWORD dwThreadID=GetCurrentThreadId();
if(InterlockedIncrement(&m_psi->lLockCount)==1){
//no other thread own the resource,own it at once
m_psi->dwThreadID=dwThreadID;
m_psi->lRecurseCount=1;
}
else{
if(m_psi->dwThreadID==dwThreadID){
//current thread own the resource,own it again
m_psi->lRecurseCount++; // 这是疑惑一 }
else{
//another thread own the resource,keep waiting until another thread release it
WaitForSingleObject(m_hEvt,INFINITE);
m_psi->lRecurseCount++;
m_psi->dwThreadID=dwThreadID;
}
}
return;
}
void COptex::Leave()
{
//release the resource
if(--m_psi->lRecurseCount>0){
//current thread still own the resource
InterlockedDecrement(&m_psi->lLockCount);
}
else{
//current thread don`t own the resource
m_psi->dwThreadID=0;
if(InterlockedDecrement(&m_psi->lLockCount)>0){ //这是疑惑二
//another thread is waiting for the resource,release it
SetEvent(m_hEvt);
}
}
return;
}
疑惑一:在上面的if已经判断出无法访问m_psi->lLockCount,也就是别的线程在使用资源,假设下面的if又判断出是这个线程在使用,这种情况是怎么会事?而且只有m_psi->lRecurseCount++; 相应的m_psi->lLockCount并没有加1
疑惑二:既然这个线程已经占据了m_psi->lLockCount,别的已经进入事件等待的线程从来都没有法子修改m_psi->lLockCount,这个值又是何时别的等待线程增加的??
void COptex::Enter()
{
//try to own the resource,keep waiting until another thread release it
if(TryEnter())
return; //current thread own the resource
DWORD dwThreadID=GetCurrentThreadId();
if(InterlockedIncrement(&m_psi->lLockCount)==1){
//no other thread own the resource,own it at once
m_psi->dwThreadID=dwThreadID;
m_psi->lRecurseCount=1;
}
else{
if(m_psi->dwThreadID==dwThreadID){
//current thread own the resource,own it again
m_psi->lRecurseCount++; // 这是疑惑一 }
else{
//another thread own the resource,keep waiting until another thread release it
WaitForSingleObject(m_hEvt,INFINITE);
m_psi->lRecurseCount++;
m_psi->dwThreadID=dwThreadID;
}
}
return;
}
void COptex::Leave()
{
//release the resource
if(--m_psi->lRecurseCount>0){
//current thread still own the resource
InterlockedDecrement(&m_psi->lLockCount);
}
else{
//current thread don`t own the resource
m_psi->dwThreadID=0;
if(InterlockedDecrement(&m_psi->lLockCount)>0){ //这是疑惑二
//another thread is waiting for the resource,release it
SetEvent(m_hEvt);
}
}
return;
}
疑惑一:在上面的if已经判断出无法访问m_psi->lLockCount,也就是别的线程在使用资源,假设下面的if又判断出是这个线程在使用,这种情况是怎么会事?而且只有m_psi->lRecurseCount++; 相应的m_psi->lLockCount并没有加1
疑惑二:既然这个线程已经占据了m_psi->lLockCount,别的已经进入事件等待的线程从来都没有法子修改m_psi->lLockCount,这个值又是何时别的等待线程增加的??
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货