4.20. Thread::AutoLock Class

Note: This class is not available with the PO_NO_THREAD_CLASSES parse option.

AutoLock objects, when used along with a Mutex object, allow Qore programmers to safely acquire and release a Mutex lock, even if exceptions are thrown or return statements are executed in the block where the AutoLock object is created. AutoLock objects are helper objects that acquire a Mutex for the lifetime of the object. For this reason, it is only appropriate to assign an AutoLock object to a local variable, so when the local variable goes out of scope, the AutoLock object will be deleted and the Mutex will be automatically released.

For example:

our Mutex $mutex();

sub check_error($error) {
    # note that the Mutex is acquired in the AutoLock constructor, and
    # the Mutex will be released as soon as the block is exited below.
    # (with either the throw statement or the return statement)
    my AutoLock $al($mutex);
    if ($error)
        throw "ERROR", "sorry, an error happened";

    return "OK";
}

Table 4.723. AutoLock Method Overview

Method

Except?

Description

AutoLock::constructor(Mutex$mutex)

Y

Creates the AutoLock object based on the Mutex argument passed and immediately calls Mutex::lock().

AutoLock::destructor()

Y

Calls Mutex::unlock() on the saved Mutex and destroys the AutoLock object.

AutoLock::copy()

Y

Throws an exception; objects of this class cannot be copied.


4.20.1. AutoLock::constructor()

Synopsis

Creates the AutoLock object based on the Mutex argument passed. The AutoLock object immediately calls Mutex::lock() on the Mutex object passed, and saves it so it can be released when the AutoLock object is destroyed.

Prototype

AutoLock::constructor(Mutex$mutex)

Example
my AutoLock $al($mutex);

Table 4.724. Arguments for AutoLock::constructor()

Argument

Description

Mutex$mutex

The Mutex object to manage for the lifetime of this object.


4.20.2. AutoLock::destructor()

Synopsis

Calls Mutex::unlock() on the saved Mutex and destroys the AutoLock object.

Example
delete $al;

4.20.3. AutoLock::copy()

Synopsis

Throws an exception; objects of this class cannot be copied.

Table 4.725. Exceptions Thrown by AutoLock::copy()

err

desc

AUTOLOCK-COPY-ERROR

Objects of this class cannot be copied.


There are no comments yet

Leave a Comment



?
? ?
?

 
Powered by TalkBack