Future
Function scheduled to run
Description
A Future object represents a function that you schedule to run in
MATLAB®.
If you use
parfevalorparfevalOnAllto create aFuture, MATLAB runs the function:In the background, if you specify
backgroundPoolwhen creating theFuture.On a parallel pool, if you do not specify
backgroundPoolwhen creating theFuture, 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
afterEachorafterAllto create aFuture, 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
parfevalto schedule a function to run in the background, on a parallel pool, or in serial.Use
parfevalOnAllto schedule a function to run on all workers in a pool, or in serial.Use
afterEachorafterAllto schedule a function to run afterFutureobjects finish.
The available types of future objects follow.
| Future Object | Description |
|---|---|
FevalFuture | Created by parfeval |
FevalOnAllFuture | Created by parfevalOnAll |
AfterEachFuture | Created by afterEach |
AfterAllFuture | Created by afterAll |
Properties
General Properties
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
Futureobject usingparfevalorafterAll, this property is a cell array orexceptionscalar. If theFutureobject completes with no error, this property is empty.If you create a
Futureobject usingafterEach, this property is a cell array with one cell for each execution of theFuturethat results in an error, or a1-by-1cell array if theFuturewas canceled. If theFutureobject completes with no error, this property is empty.If you create a
Futureobject usingparfevalOnAll, this property is a cell array with one cell for each worker if any errors occurred on the workers, or a1-by-1cell array if theFuturewas canceled. If theFutureobject 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
FutureusingparfevalorparfevalOnAll, MATLAB runs the function in the background, on a parallel pool (if you have Parallel Computing Toolbox), or in serial.If you create the
FutureusingafterEachorafterAll, 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'—Futureis queued, and the function associated with it is scheduled to run.'running'— Function associated with theFutureis currently running.'finished'— Function associated with theFutureis finished running.'unavailable'—Futureis unable to run. Elements of a preallocatedFuturearray have this state.
FevalFuture Properties
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 Properties
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
afterAll | Run function after all functions finish running in the background |
afterEach | Run function after each function finishes running in the background |
cancel | Stop function running in the background |
fetchOutputs | Retrieve results from function running in the background |
wait | Wait for futures to complete |
fetchNext | Retrieve next unread outputs from Future array |
Examples
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.
When you run a function in the background using parfeval, you create a Future object. If you have multiple parfeval computations running in the background, you can keep track of the computations by storing the Future objects in an array.
For efficiency, preallocate an array of Future objects.
N = 100; F(1:N) = parallel.Future;
Run a for-loop with N iterations. In each iteration, use parfeval to compute the rank of magic squares in the background. Store each Future object in the array of Future objects, F.
for idx = 1:N F(idx) = parfeval(backgroundPool,@rank,1,magic(idx)); end
You can retrieve the outputs from the individual Future objects as they become available by using the fetchNext function. Alternatively, use the fetchOutputs function to wait for all the computations to finish before retrieving outputs from all the Future objects.
out = fetchOutputs(F);
disp("Background computations complete.")Background computations complete.
Tips
Futureobjects are local objects and can be accessed only in the MATLAB session that created them.For example, if you use
parfevalto run a function in the background and create aFutureobject, theFutureis not available in the workspace of background workers.
Extended Capabilities
The Future function fully supports
thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
Version History
Introduced in R2013b
See Also
parallel.Pool (Parallel Computing Toolbox) | parfeval (Parallel Computing Toolbox) | parfevalOnAll (Parallel Computing Toolbox) | afterAll | afterEach
MATLAB Command
You clicked a link that corresponds to this MATLAB command:
Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.
Sélectionner un site web
Choisissez un site web pour accéder au contenu traduit dans votre langue (lorsqu'il est disponible) et voir les événements et les offres locales. D’après votre position, nous vous recommandons de sélectionner la région suivante : .
Vous pouvez également sélectionner un site web dans la liste suivante :
Comment optimiser les performances du site
Pour optimiser les performances du site, sélectionnez la région Chine (en chinois ou en anglais). Les sites de MathWorks pour les autres pays ne sont pas optimisés pour les visites provenant de votre région.
Amériques
- América Latina (Español)
- Canada (English)
- United States (English)
Europe
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)