C++ Boost

Boost.Threads

basic_trylock


This template class defines a lock type that allows the program to attempt to lock the associated mutex model with out blocking. The try_mutex, timed_mutex, recursive_try_mutex and recursive_timed_mutex use this template to define their try_lock types.

Like all the Boost.Threads lock models, the basic_trylock is meant to be short lived and is not thread-safe, so should not be shared between threads.

Header

#include <boost/thread/xlock.hpp>
   This header is usually not included directly by programmers.

Public Interface


    template <typename M>
    class basic_trylock : private boost::noncopyable
    {
    public:
        typedef M mutex_type;
        
        explicit basic_trylock(M& mx);
        basic_trylock(M& mx, bool lock_it);
        ~basic_trylock();
        
        void lock();
        bool try_lock();
        void unlock();
        
        operator const void*() const;
    };

Constructors

    explicit basic_trylock(M& mx);

Constructs a basic_trylock and calls try_lock.

    basic_trylock(M& mx, bool lock_it);

Constructs a basic_trylock and if lock_it is true then calls lock.

Destructor

    ~basic_trylock();

Destructs the basic_trylock and if locked calls unlock.

lock

    void lock();

Locks the associated mutex model. If the basic_trylock is already locked then a lock_error is thrown. Depending on the locking strategy of the mutex model if the calling thread already owns a lock through another lock model this may cause a deadlock or for a lock_error to be thrown.

try_lock

    bool try_lock();

Attempts to lock the associated mutex_model. If the basic_trylock is already locked then a lock_error is thrown. If the mutex model is already locked by another thread this attempt fails immediately with out blocking and returns false.

unlock

    void unlock();

Unlocks the associated mutex model. If the basic_trylock is not already locked then a lock_error is thrown.

const void* Conversion

    operator const void*() const;

Implicitly converts the lock to a value that can be used in boolean expressions to test if the lock is currently locked or not.

Example Usage

#include <boost/thread/mutex.hpp>
#include <iostream>

int main(int, char*[])
{
   boost::mutex mutex;
   boost::mutex::try_lock lock(mutex);
   if (lock)
      std::cout << "locked" << std::endl;
   else
      std::cout << "unlocked" << std::endl;
   return 0;
}

The output is:

locked

Copyright William E. Kempf 2001 all rights reserved.