有没有办法在没有锁的情况下同步这个?

时间:2016-01-26 15:24:31

标签: c++ c windows synchronization kernel-mode

假设我有3个可由上层调用的函数:

  • Start - 只有在我们尚未启动时才会被调用,或者之前被称为停止
  • Stop - 只有在成功调用Start
  • 后才会调用
  • Process - 可以在任何时间调用(同时在不同的线程上);如果开始,将调用下层

Stop中,它必须等待所有Process次呼叫完成对较低层的呼叫,并阻止进一步呼叫。使用锁定机制,我可以提出以下伪代码:

Start() {
  ResetEvent(&StopCompleteEvent);
  IsStarted = true;
  RefCount = 0;
}

Stop() {
   AcquireLock();
   IsStarted = false;
   WaitForCompletionEvent = (RefCount != 0);
   ReleaseLock();
   if (WaitForCompletionEvent)
     WaitForEvent(&StopCompleteEvent);
   ASSERT(RefCount == 0);
}

Process() {
  AcquireLock();
  AddedRef = IsStarted;
  if (AddedRef)
    RefCount++;
  ReleaseLock();

  if (!AddedRef) return;

  ProcessLowerLayer();

  AcquireLock();
  FireCompletionEvent = (--RefCount == 0);
  ReleaseLock();
  if (FilreCompletionEvent)
    SetEvent(&StopCompleteEvent);
}

有没有办法在没有锁定机制的情况下实现相同的行为?或许有一些使用InterlockedCompareExchange和InterlockedIncremenet / InterlockedDecrement?

我问的原因是这是在网络驱动程序的数据路径中,我真的不想有任何锁定。

1 个答案:

答案 0 :(得分:2)

我相信可以避免使用显式锁和任何不必要的阻塞或内核调用。

请注意,这只是伪代码,仅用于说明目的;它没有见过编译器。虽然我认为线程逻辑是合理的,但请自行验证其正确性,或让专家对其进行验证;无锁编程是 hard

#define STOPPING 0x20000000;
#define STOPPED 0x40000000;
volatile LONG s = STOPPED;
  // state and count
  // bit 30 set -> stopped
  // bit 29 set -> stopping
  // bits 0 through 28 -> thread count

Start() 
{
   KeClearEvent(&StopCompleteEvent);
   LONG n = InterlockedExchange(&s, 0);  // sets s to 0
   if ((n & STOPPED) == 0) 
       bluescreen("Invalid call to Start()");
}

Stop()
{
   LONG n = InterlockedCompareExchange(&s, STOPPED, 0);
   if (n == 0)
   {
       // No calls to Process() were running so we could jump directly to stopped.
       // Mission accomplished!
       return;
   }

   LONG n = InterlockedOr(&s, STOPPING);
   if ((n & STOPPED) != 0)
       bluescreen("Stop called when already stopped");
   if ((n & STOPPING) != 0)
       bluescreen("Stop called when already stopping");

   n = InterlockedCompareExchange(&s, STOPPED, STOPPING);
   if (n == STOPPING)
   {
       // The last call to Process() exited before we set the STOPPING flag.
       // Mission accomplished!
       return;
   }

   // Now that STOPPING mode is set, and we know at least one call to Process 
   // is running, all we need do is wait for the event to be signaled.

   KeWaitForSingleObject(...);

   // The event is only ever signaled after a thread has successfully
   // changed the state to STOPPED.  Mission accomplished!

   return;
}

Process()
{
    LONG n = InterlockedCompareExchange(&s, STOPPED, STOPPING);
    if (n == STOPPING)
    {
         // We've just stopped; let the call to Stop() complete.
         KeSetEvent(&StopCompleteEvent);
         return;
    }
    if ((n & STOPPED) != 0 || (n & STOPPING) != 0)
    {
         // Checking here avoids changing the state unnecessarily when
         // we already know we can't enter the lower layer.

         // It also ensures that the transition from STOPPING to STOPPED can't
         // be delayed even if there are lots of threads making new calls to Process().

         return;
    }

    n = InterlockedIncrement(&s);
    if ((n & STOPPED) != 0)
    {
        // Turns out we've just stopped, so the call to Process() must be aborted.

        // Explicitly set the state back to STOPPED, rather than decrementing it,
        // in case Start() has been called.  At least one thread will succeed.
        InterlockedCompareExchange(&s, STOPPED, n);
        return;
    }

    if ((n & STOPPING) == 0)
    {
        ProcessLowerLayer();
    }

    n = InterlockedDecrement(&s);
    if ((n & STOPPED) != 0 || n == (STOPPED - 1))
        bluescreen("Stopped during call to Process, shouldn't be possible!");

    if (n != STOPPING)
        return;

    // Stop() has been called, and it looks like we're the last 
    // running call to Process() in which case we need to change the 
    // status to STOPPED and signal the call to Stop() to exit.

    // However, another thread might have beaten us to it, so we must 
    // check again.  The event MUST only be set once per call to Stop().

    n = InterlockedCompareExchange(&s, STOPPED, STOPPING);
    if (n == STOPPING)
    {
         // We've just stopped; let the call to Stop() complete.
         KeSetEvent(&StopCompleteEvent);
    }
    return;
}