ScopedTryLock

I found I missed such a creature. Tried to keep it in good JUCE spirit :slight_smile: :

//==============================================================================
/**
    Automatically tries to lock and unlock a CriticalSection object.

    Use one of these as a local variable to control access to a CriticalSection.

    e.g. @code

    CriticalSection myCriticalSection;

    for (;;)
    {
        const ScopedTryLock myScopedTryLock (myCriticalSection);
        // Check if myCriticalSection is locked, and only access protected variables then.
        // This is useful in situations where you can't afford waiting for another thread to unlock the CriticalSection
        if (myScopedTryLock.isLocked())
        {   
           ...do some stuff...
        }	

        // myCriticalSection gets unlocked here (if it waslocked)
    }
    @endcode

    @see CriticalSection, ScopedUnlock, ScopedLock
*/
class JUCE_API  ScopedTryLock
{
public:
    //==============================================================================
    /** Creates a ScopedTryLock.

        As soon as it is created, this will try to lock the CriticalSection, and
        when the ScopedTryLock object is deleted, the CriticalSection will
        be unlocked if the lock was successful. 
   
        Make sure this object is created and deleted by the same thread,
        otherwise there are no guarantees what will happen! Best just to use it
        as a local stack object, rather than creating one with the new() operator.
    */
    inline ScopedTryLock (const CriticalSection& lock) throw()     : lock_ (lock) { lockWasSuccessful_ = lock.tryEnter(); }

    /** Destructor.

        The CriticalSection will be unlocked (if locked) when the destructor is called.

        Make sure this object is created and deleted by the same thread,
        otherwise there are no guarantees what will happen!
    */
    inline ~ScopedTryLock() throw()                                { if (lockWasSuccessful_) lock_.exit(); }

    /** Lock state 
	
    @return True if the CriticalSection is locked.
    */
    inline bool isLocked() const { return lockWasSuccessful_; }
	
private:
    //==============================================================================
    const CriticalSection& lock_;
    bool lockWasSuccessful_;

    ScopedTryLock (const ScopedTryLock&);
    const ScopedTryLock& operator= (const ScopedTryLock&);
};
1 Like

Not bad! Almost what I would have written msyself!

Thanks, I’ll throw that into the build if you like.

[quote=“jules”]Not bad! Almost what I would have written msyself!

Thanks, I’ll throw that into the build if you like.[/quote]

:slight_smile: I’d appreciate that, thanks!