-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathParallelBlock.m
84 lines (75 loc) · 2.43 KB
/
ParallelBlock.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
classdef ParallelBlock < handle
% ParallelBlock is a simple class that provides syntactic sugar for
% managing calls to start and stop matlab pool
% Create a ParallelBlock object to guarantee the matlab pool is open
% (if it's available). Call parBlock.endBlock() to close the pool
% (unless it was active before the block was constructed, or another
% ParallelBlock is keeping it open).
% When the ParallelBlock object is deleted, it automatically calls
% endBlock(), so attaching a ParallelBlock object to another object will
% guarantee that the matlab pool is open for the duration of the parent
% objects life, and will shut it down (if it's no longer necessary) when
% the parent object is destroyed
properties (SetAccess = public)
% public properties go here
end
properties (SetAccess = protected)
blocked % boolean, true if 'matlabpool close' must be invoked at
% the end of the block
end
methods
% constructor
function parBlock = ParallelBlock()
% guarantee parallel environment is active (if available)
parBlock.blocked = false;
parBlock.startBlock();
end
function startBlock(parBlock)
% guarantee parallel environment is active (if available)
if parBlock.blocked
% already blocked, quietly return
return
else
parBlock.blocked = true;
end
global numParallelBlocks
global needStopPool
if isempty(numParallelBlocks)
numParallelBlocks = 0;
end
if numParallelBlocks == 0
if ParallelIsActive()
needStopPool = false;
else
try
matlabpool
needStopPool = true;
catch %#ok<CTCH>
needStopPool = false;
end
end
end
numParallelBlocks = numParallelBlocks + 1;
end
function endBlock(parBlock)
% release parallel environment is active (if no longer necessary)
if parBlock.blocked
parBlock.blocked = false;
else
% already released, quietly do nothing
return
end
global numParallelBlocks
global needStopPool
numParallelBlocks = numParallelBlocks - 1;
if (numParallelBlocks == 0) && needStopPool && matlabpool('size') > 0
matlabpool close
end
end
end
methods (Access = protected)
function delete(parBlock)
parBlock.endBlock();
end
end
end