forked from automl/HPOlib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLocker.py
executable file
·70 lines (63 loc) · 2.38 KB
/
Locker.py
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
##
# Copyright (C) 2012 Jasper Snoek, Hugo Larochelle and Ryan P. Adams
#
# This code is written for research and educational purposes only to
# supplement the paper entitled
# "Practical Bayesian Optimization of Machine Learning Algorithms"
# by Snoek, Larochelle and Adams
# Advances in Neural Information Processing Systems, 2012
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import time
def safe_delete(filename):
cmd = 'mv "%s" "%s.delete" && rm "%s.delete"' % (filename, filename,
filename)
fail = os.system(cmd)
return not fail
class Locker:
def __init__(self):
self.locks = {}
def __del__(self):
for filename in self.locks.keys():
self.locks[filename] = 1
self.unlock(filename)
def lock(self, filename):
if self.locks.has_key(filename):
self.locks[filename] += 1
return True
else:
cmd = 'ln -s /dev/null "%s.lock" 2> /dev/null' % (filename)
fail = os.system(cmd)
if not fail:
self.locks[filename] = 1
return not fail
def unlock(self, filename):
if not self.locks.has_key(filename):
sys.stderr.write("Trying to unlock not-locked file %s.\n" %
(filename))
return True
if self.locks[filename] == 1:
success = safe_delete('%s.lock' % (filename))
if not success:
sys.stderr.write("Could not unlock file: %s.\n" % (filename))
del self.locks[filename]
return success
else:
self.locks[filename] -= 1
return True
def lock_wait(self, filename):
while not self.lock(filename):
time.sleep(0.01)