Main Content

Future

Function scheduled to run

Description

A Future object represents a function that you schedule to run in MATLAB®.

  • If you use parfeval or parfevalOnAll to create a Future, MATLAB runs the function:

    • In the background, if you specify backgroundPool when creating the Future.

    • On a parallel pool, if you do not specify backgroundPool when creating the Future, have Parallel Computing Toolbox™ and one of the following applies:

      • You have a parallel pool currently open.

      • You have automatic pool creation enabled.

    • In serial, otherwise.

  • If you use afterEach or afterAll to create a Future, the function is run by your current MATLAB session. It is not run in the background or on any parallel pool.

Creation

You create a Future object when you do one of the following:

  • Use parfeval to schedule a function to run in the background, on a parallel pool, or in serial.

  • Use parfevalOnAll to schedule a function to run on all workers in a pool, or in serial.

  • Use afterEach or afterAll to schedule a function to run after Future objects finish.

The available types of future objects follow.

Future ObjectDescription
FevalFutureCreated by parfeval
FevalOnAllFutureCreated by parfevalOnAll
AfterEachFutureCreated by afterEach
AfterAllFutureCreated by afterAll

Properties

expand all

General Options

This property is read-only.

Date and time when the Future object was created, specified as a datetime scalar.

This property is read-only.

Error information, specified as an MException scalar or cell array of exception objects.

  • If you create a Future object using parfeval or afterAll, this property is a cell array or exception scalar. If the Future object completes with no error, this property is empty.

  • If you create a Future object using afterEach, this property is a cell array with one cell for each execution of the Future that errored, or a 1-by-1 cell array if the Future was canceled. If the Future object completes with no error, this property is empty.

  • If you create a Future object using parfevalOnAll, this property is a cell array with one cell for each worker if any errors occurred on the workers, or a 1-by-1 cell array if the Future was canceled. If the Future object completes with no error, this property is empty.

For more information about errors encountered when you schedule a function to run after Future objects finish, see afterEach and afterAll.

This property is read-only.

Date and time when the function finished, specified as a datetime scalar.

The Future finishes running when MATLAB finishes running the function associated with it.

If the function associated with the Future object is not finished running, this property is an empty datetime array.

Data Types: datetime

This property is read-only.

Function associated with the Future object, specified as a function handle.

  • If you create the Future using parfeval or parfevalOnAll, MATLAB runs the function in the background, on a parallel pool (if you have Parallel Computing Toolbox), or in serial.

  • If you create the Future using afterEach or afterAll, the function is run by your current MATLAB session. It is not run in the background or on any parallel pool.

Example: @magic

Data Types: function_handle

This property is read-only.

Identifier, specified as an integer scalar.

Data Types: double

This property is read-only.

Input arguments for the function, specified as a cell array.

When the scheduled function fcn specified by the Function property runs, it runs as fcn(X{:}), where X is the cell array of input arguments specified by this property.

Example: {[1]}

Example: {[1,2], [2,1]}

Data Types: cell

This property is read-only.

Number of arguments returned by the function, specified as an integer scalar.

The function specified by the Function property must return at least as many arguments as specified by this property.

Data Types: double

This property is read-only.

Output arguments from running the function, specified as a cell array.

This property is an empty cell array if the Future object is not finished running or the Future object completes with an error.

Example: {[3.14]}

Data Types: cell

Current duration of the Future object, specified as a duration scalar.

When the Future object finishes running, this property becomes constant.

This property is read-only.

Date and time when the Future object started running, specified as a datetime scalar.

The Future starts running when MATLAB starts running the function associated with it.

Data Types: datetime

This property is read-only.

Current state of the future, specified as one of these values:

  • 'queued'Future is queued, and the function associated with it is scheduled to run.

  • 'running' — Function associated with the Future is currently running.

  • 'finished' or 'failed' — Function associated with the Future is finished running.

  • 'unavailable'Future is unable to run. Elements of a preallocated Future array have this state.

FevalFuture Options

This property is read-only.

Text output, specified as a character vector.

This property is a character vector containing all text that is displayed if you explicitly run the functions specified by the Function property using the input arguments specified by the InputArguments property.

This property is read-only.

Queue of Future objects, specified as a parallel.FevalQueue object.

This property is equal to the queue of Future objects given by the FevalQueue of the pool that the future is running on.

This property is not available for Future objects that run functions in a thread-based environment.

This property is read-only.

Flag indicating if outputs have been read, specified as true or false.

This property is set to true only if you use fetchOutputs or fetchNext.

Data Types: logical

FevalOnAllFuture Options

This property is read-only.

Recorded text, specified as a cell array of character vectors.

This property is a cell array containing all text that is displayed if you explicitly run the functions specified by the Function property using the input arguments specified by the InputArguments property.

The jth element of the array is the text output captured from the jth worker in the pool that ran the Future.

Data Types: cell

This property is read-only.

Queue of Future objects, specified as a parallel.FevalQueue object.

This property is equal to the queue of Future objects given by the FevalQueue of the pool that the future is running on.

This property is not available for Future objects that run functions in a thread-based environment.

Object Functions

expand all

afterAllRun function after all functions finish running in the background
afterEachRun function after each function finishes running in the background
cancelStop function running in the background
fetchOutputsRetrieve results from function running in the background
waitWait for futures to complete
fetchNextRetrieve next unread outputs from Future array

Examples

collapse all

This example shows how to use afterEach to schedule a callback function to run after a function finishes running in the background.

Use parfeval to run the function rand(1) and retrieve one output. Specify backgroundPool as the first argument to run the function in the background. Repeat 10 times to create 10 Future objects.

for i = 1:10
    f(i) = parfeval(backgroundPool,@rand, 1, 1);
end

After each Future finishes, display the value using the disp function. The input arguments for disp are the output arguments from each Future. Specify the third argument to the afterEach function as 0 to return no outputs from the callback.

afterEach(f,@disp,0);

This example shows how to use afterEach to update a wait bar with the progress of functions running in the background.

Create a wait bar, w.

w = waitbar(0,'Please wait ...');

Set the number of iterations for your for-loop, N. Store the current number of completed iterations, 0, and the total number of iterations, N, in the UserData property of the wait bar.

N = 20;
w.UserData = [0 N];

Run a for-loop with N iterations. In each iteration, use parfeval and backgroundPool to run pause in the background for a random number of seconds. Store each Future object in an array.

for i = 1:N
    delay = rand;
    f(i) = parfeval(backgroundPool,@pause,0,delay);
end

Use the helper function updateWaitbar to update the waitbar after each Future finishes.

afterEach(f,@(~)updateWaitbar(w),0);

Use delete to close the wait bar after all the Future objects finish.

afterAll(f,@(~)delete(w),0);

Define Helper Function

Define the helper function updateWaitbar. The function increments the first element of the UserData property, then uses the vector to calculate the progress.

function updateWaitbar(w)
    % Update a waitbar using the UserData property.

    % Check if the waitbar is a reference to a deleted object
    if isvalid(w)
        % Increment the number of completed iterations 
        w.UserData(1) = w.UserData(1) + 1;

        % Calculate the progress
        progress = w.UserData(1) / w.UserData(2);

        % Update the waitbar
        waitbar(progress,w);
    end
end

This example shows how to stop a MATLAB function that you are running in the background. When you use parfeval to run a function in the background, MATLAB immediately returns a Future object. Long-running functions can block other functions from running in the background. To stop the function from running, you must use the cancel function instead of selecting Live Editor > Run > Stop.

Use parfeval to run pause(Inf) without retrieving any outputs. Specify backgroundPool as the first argument to run the function in the background. When you use parfeval, you create a Future object.

f = parfeval(backgroundPool,@pause,0,Inf);

Check the state of the Future object.

f.State
ans = 
'running'

When you run parfeval, you schedule a function to run in the background. When the background pool has insufficient resources to run the function, the Future is in the 'queued' state. When the function is run by the background pool, the Future is in the 'running' state.

To stop the function from running in the background, cancel the Future object.

cancel(f)
f.State
ans = 
'finished'

The function is now in the 'finished' state.

Tips

  • Future objects are local objects and can be accessed only in the MATLAB session that created them.

    For example, if you use parfeval to run a function in the background and create a Future object, the Future is not available in the workspace of background workers.

Extended Capabilities

Version History

Introduced in R2013b

See Also

(Parallel Computing Toolbox) | (Parallel Computing Toolbox) | (Parallel Computing Toolbox) | |