Boost deadlock related issues

◆ Realization of read-write lock

typedef boost::shared_lock<boost::shared_mutex> readLock;

typedef boost:: unique_lock<boost::shared_mutex> writeLock;

 

boost::shared_mutex  rwmutex;

 

void readOnly( )

{

        readLock  rdlock( rwmutex );

        /// do something

}

 

void writeOnly( )

{

        writeLock  wtlock( rwmutex );

        /// do something

}

For the same rwmutex, threads can have multiple readLocks at the same time. These readLocks will block any thread that attempts to obtain writeLock until all readLock objects are destroyed. If writeLock obtains rwmutex first, it will block any thread that attempts to obtain readLock or writeLock on rwmutex.

▼Recursive mutex

boost::recursive_mutex provides a recursive mutex. For an instance, at most one thread is allowed to hold its lock. If a thread has locked a boost::recursive_mutex instance, then this thread can lock this instance multiple times.

lock_guard can only be used as above, while unique_lock allows setting a timeout, postponing locking of the lock and unlocking before the object is destroyed.

{

    boost::unique_lock<boost::mutex> lk( m );

    process( data );

    lk.unlock( );

    // do other thing

};

★Set lock timeout

boost::unique_lockboost::timed_mutex lk( m, std::chrono::milliseconds(3) ); // timeout 3 seconds

if( lk ) process( data );

◆ upgrade_lock类

What is upgrade_lock, its biggest feature is that it is not mutually exclusive with shared_lock, and mutually exclusive with other upgrade_lock and unique_lock. That is to say, after thread A obtains the mutex's upgrade_lock, threads B, C, etc. can also obtain the mutex's share_mutex, and vice versa.

It is not limited to exclusive locks provided by lockable pairs, but also supports upgradeable locks.

Note:
When the code of the write lock is nested with the code of the read lock, it will cause a deadlock! ! ! Examples are as follows:

boost::shared_mutex m_mutex;

void test()
{
	boost::shared_lock<boost::shared_mutex> ReadLock(m_mutex);
}

int main()
{
	...................................
	boost::unique_lock<boost::shared_mutex> WriteLock(m_mutex);
	....................................
	{
    	test();
	}
   ....................................
}

Since the lock has been acquired in main, if you want to acquire the read lock again when executing test(), you need to wait for the write lock in main to be released. But the write lock will not be released, and the read lock in the test will wait forever.

Guess you like

Origin blog.csdn.net/qq_23350817/article/details/109182443