0

I'm writing a transform filter in Directshow. I've looked at the Transform filter implementation.
They use 1 filter_lock for protecting filter's state and another lock called streaming_lock for protecting resources used in streaming thread. But in the streaming thread, the default implementation accesses the filter's state without filter_lock. eg: CTransformInputPin::Receive>CBaseInputPin::Receive>CTransformInputPin::CheckStreaming>CBasePin::IsStopped>accessing m_State.
Isn't that data race if they change m_State in Pause() while the filter's is in Running_State and checking the m_State in streaming thread?

P/s: I think the simple solution to avoid data race in the m_state is making it atomic or creating separate lock for m_state. This also keeps the existing logic basically unchanged. eg:

CTransformInputPin::CheckStreaming() {
 // check something...

 // check m_state
 {
  CAutoLock lck1(m_filter->stateLock);
  if (IsStopped()) {
   return VFW_E_WRONG_STATE;
  }
 }

}
CTransformFilter::Pause() // or Stop(), Run()
{
 CAutoLock lck(&m_csFilter);
 // logic....
 
 // when need to set m_state
 {
  CAutoLock lck1(stateLock);
  m_State = State_Paused;
 }
}

Update: It seems that Windows will guarantee atomic access to word/dword-sized variables like m_state. So it is now a relief to me.

irous
  • 401
  • 3
  • 8
  • The purpose of a lock is to make sure the object cannot be in an inconsistent state. When there is a single variable like this, there is no possibility for failure. Accessing `m_State` will be atomic. You'll either get the old value or the new value, but you can't get an inconsistent value. – Tim Roberts May 01 '22 at 06:36
  • @TimRoberts I read some posts they said that plain C/C++ variable like ``m_state`` is not atomic, just some architectures will guarantee it atomic but not all. – irous May 01 '22 at 06:52
  • 1
    Technically true, but since this code is very specific for WIndows, and Windows only runs on x86/x64 and ARM, they don't have to worry about that. It's worth pointing out that DirectShow was originally written in 1993. It has survived nearly three decades of EXTENSIVE practical use. I'm not saying it's error-free, but it is very nearly so. – Tim Roberts May 01 '22 at 06:55

0 Answers0