When to use recursive mutex?

后端 未结 6 613
旧时难觅i
旧时难觅i 2020-11-30 19:36

I understand recursive mutex allows mutex to be locked more than once without getting to a deadlock and should be unlocked the same number of times. But in what specific sit

6条回答
  •  长情又很酷
    2020-11-30 20:29

    I encountered the need for a recursive mutex today, and I think it's maybe the simplest example among the posted answers so far: This is a class that exposes two API functions, Process(...) and reset().

    public void Process(...)
    {
      acquire_mutex(mMutex);
      // Heavy processing
      ...
      reset();
      ...
      release_mutex(mMutex);
    }
    
    public void reset()
    {
      acquire_mutex(mMutex);
      // Reset
      ...
      release_mutex(mMutex);
    }
    

    Both functions must not run concurrently because they modify internals of the class, so I wanted to use a mutex. Problem is, Process() calls reset() internally, and it would create a deadlock because mMutex is already acquired. Locking them with a recursive lock instead fixes the problem.

提交回复
热议问题