4.19. 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 = new 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 $am = new AutoLock($mutex);
    if ($error)
        throw "ERROR", "sorry, an error happened";

    return "OK";
}

Table 4.850. AutoLock Method Overview

Method

Except?

Description

AutoLock::constructor()

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.19.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.

Usage
new AutoLock(mutex_object)
Example
my $al = new AutoLock($mutex);

Table 4.851. Arguments for AutoLock::constructor()

Argument

Type

Description

$mutex

Mutex

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


Table 4.852. Return Values for AutoLock::constructor()

Return Type

Description

AutoLock Object

The new AutoLock object.


4.19.2. AutoLock::destructor()

Synopsis

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

Usage
delete lvalue
Example
delete $al;

4.19.3. AutoLock::copy()

Synopsis

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

Table 4.853. Arguments for AutoLock::copy()

Argument

Type

Description

n/a

n/a

This method takes no arguments.


Table 4.854. Return Values for AutoLock::copy()

Return Type

Description

n/a

This method returns no value because it throws an exception.


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

err

desc

AUTOLOCK-COPY-ERROR

Objects of this class cannot be copied.