Home > atmlab > files > get_lock.m

get_lock

PURPOSE ^

getlock Acquire lock

SYNOPSIS ^

function fullpath = get_lock(d, f, varargin)

DESCRIPTION ^

 getlock   Acquire lock

 This function creates an empty file and tries to move it to a lockfile
 destination.  If the lockfile destination already exists, it will wait
 until it does not.  However, it will not wait longer than a timeout that
 the user may specify as a 3rd option.

 When done, just remove the lockfile.  I mean, really!

 IN

   d         directory where lockfile shall be created
   f         name of the lockfile (not including directory)
   timeout   maximum length in second to wait.  Defaults to 120 seconds.

 OUT

   the full path to the lockfile

CROSS-REFERENCE INFORMATION ^

This function calls: This function is called by:

DOWNLOAD ^

get_lock.m

SOURCE CODE ^

0001 function fullpath = get_lock(d, f, varargin)
0002 
0003 % getlock   Acquire lock
0004 %
0005 % This function creates an empty file and tries to move it to a lockfile
0006 % destination.  If the lockfile destination already exists, it will wait
0007 % until it does not.  However, it will not wait longer than a timeout that
0008 % the user may specify as a 3rd option.
0009 %
0010 % When done, just remove the lockfile.  I mean, really!
0011 %
0012 % IN
0013 %
0014 %   d         directory where lockfile shall be created
0015 %   f         name of the lockfile (not including directory)
0016 %   timeout   maximum length in second to wait.  Defaults to 120 seconds.
0017 %
0018 % OUT
0019 %
0020 %   the full path to the lockfile
0021 
0022 % $Id: get_lock.m 8516 2013-06-26 21:33:48Z gerrit $
0023 
0024 timeout = optargs(varargin, {120});
0025 
0026 t = tempname(d);
0027 fp = fopen(t, 'w');
0028 fclose(fp);
0029 fullpath = fullfile(d, f);
0030 
0031 interval = 0.1;
0032 t1 = tic();
0033 success = false;
0034 logtext(atmlab('OUT'), 'Trying to create lockfile at %s\n', fullpath);
0035 while toc(t1) < timeout
0036     exec_system_cmd(sprintf('mv -n %s %s', ...
0037         t, fullpath));
0038     % if original still exists, then mv -n (NOCLOBBER) failed
0039     if exist(t, 'file')
0040         pause(interval);
0041         if mod(toc(t1), 5) < 0.2
0042             logtext(atmlab('OUT'), 'Waiting for lockfile after %.3f seconds\n', toc(t1));
0043         end
0044     else
0045         logtext(atmlab('OUT'), 'Succesfully created lockfile\n');
0046         success = true;
0047         break
0048     end
0049 end
0050 
0051 if ~success
0052     error(['atmlab:' mfilename ':nolock'], ...
0053         'No lock after waiting for %d seconds', timeout);
0054 end
0055 
0056 end

Generated on Mon 15-Sep-2014 13:31:28 by m2html © 2005