Skip to Main Content
Intel Threading Building Blocks
book

Intel Threading Building Blocks

by James Reinders
July 2007
Intermediate to advanced content levelIntermediate to advanced
332 pages
10h 4m
English
O'Reilly Media, Inc.
Content preview from Intel Threading Building Blocks

Upgrade/Downgrade

It is possible to upgrade a reader lock to a writer lock by using the method upgrade_ to_writer. Here is an example:

	std::vector<string> MyVector;
	typedef spin_rw_mutex MyVectorMutexType;
	MyVectorMutexType MyVectorMutex;

	void AddKeyIfMissing( const string& key ) {
	    // Obtain a reader lock on MyVectorMutex
	    MyVectorMutexType::scoped_lock lock(MyVectorMutex,/*is_writer=*/false);
	    size_t n = MyVector.size();
	    for( size_t i=0; i<n; ++i )
	        if( MyVector[i]==key ) return;
	    if( !MyVectorMutex.upgrade_to_writer() )
	        // Check if key was added while lock was temporarily released
	        for( int i=n; i<MyVector.size(); ++i )
	           if(MyVector[i]==key ) return;
	    vector.push_back(key);
	}

Note that after obtaining a lock on the vector, the routine must sometimes search the vector again. This is necessary because upgrade_to_writer might have to temporarily release the lock before it can upgrade. Otherwise, deadlock might ensue. The upgrade_to_writer method returns a bool that is true if it successfully upgrades the lock without releasing it, and false if the lock is released temporarily. Thus, when upgrade_to_writer returns false, the code must rerun the search to check that the key was not inserted by another writer. The example presumes that keys are always added to the end of the vector, and that keys are never removed. Because of these assumptions, it does not have to re-search the entire vector, but only the elements beyond those originally searched. The critical point to remember is that when ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Intel® Xeon Phi™ Coprocessor Architecture and Tools: The Guide for Application Developers

Intel® Xeon Phi™ Coprocessor Architecture and Tools: The Guide for Application Developers

Rezaur Rahman

Publisher Resources

ISBN: 9780596514808Errata Page