c++ - 有没有办法在没有锁的情况下同步它?

标签 c++ c windows synchronization kernel-mode

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

  • Start - 仅当我们尚未开始或之前调用过 Stop 时才会被调用
  • 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 的一些奇特用法?

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

最佳答案

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

请注意,这只是伪代码,仅供说明之用;它还没有看到编译器。虽然我相信线程逻辑是合理的,但请自行验证其正确性,或请专家验证;无锁编程很难

#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;
}

关于c++ - 有没有办法在没有锁的情况下同步它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35017416/

相关文章:

c++ - 我如何(或应该)在链表中使用指针

c++ - 在 C++ 中立即退出 'while' 循环

c++ - 如何设置 boost.log 来限制日志文件的数量

c++ - 在 QPixmap 中写入文本

windows - 使用 EnableDelayedExpansion 时变量修饰符的正确语法

windows - Go中终止进程的跨平台方式

windows - 卸载由不存在的用户安装的 Windows 应用程序

c++ - 从循环中的 QStandardItem 中删除项目

c - 嵌入式设备上的强大 RS232 串行通信方案是什么?

c - 了解 C 中的字符数组相等性