Pregunta

I have a class that opens transactions, adds operations to a queue, then closes the transaction. Across the open->close lifetime I would like to employ a recursive mutex, so that only one thread can have a transaction open at any time. All other threads are blocked until the current transaction is ended.

class MyObject
{
  void beginTransaction()
  {
    // acquire mutex
  }

  void endTransaction()
  {
    // release mutex
  }

  boost::recursive_mutex m_mutex;
}

I am having difficulty determining how I can use a recursive_mutex in this case, as the lock would exist longer than the scope of a single method. Can anyone suggest how I might apply locking here?

¿Fue útil?

Solución

Boost (and the standard library) provide mutexes, which can be locked and unlocked, and locks, which lock mutexes in their constructor and unlocks them in their destructor. Locks are really just lightweight wrappers that are used to ensure a lock is released when leaving scope.

In your case, you would just use the mutex directly, without wrapping it in a lock.

You can call m_mutex.lock() in beginTransaction to lock the mutex, then m_mutex.unlock() in endTransaction to unlock the mutex. If another thread attempts to call m_mutex.lock() between calls, it will block until the mutex is unlocked by the owning thread in endTransaction

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top