concurrency - python: write file once across concurrent independent invocations -
i have situation multiple concurrent invocations of python script takes place involving initializing , loading system info in file.
this initialization should happen once , while happening other invocations must wait somehow. , when has happened, other invocations must proceed reading file. however, since unknown number of concurrent invocation of program taking place, section entered multiple times causing problems.
here code:
#initialization has happened, load info file if os.path.isfile("/tmp/corners.txt"): logging.info("corners exist, load'em up!") #load corners cornersfile cornersfile=open("/tmp/corners.txt","r") line in cornersfile: corners.append((line.split()[0], line.split()[1]))` cornersfile.close() logging.info("corners %s", corners) else: # initialize , not let other concurrent invocations proceed! logging.info("initiation not done, it!") #init blocks , return list of corners #write corners file cornersfile=open("/tmp/corners.txt", "w") cornersfile.write("\n".join('%s %s' % x x in corners)) cornersfile.close() i did testing running code 8 times concurrently. in logs, see first part of code enters thrice , else part entered 5 times.
how make sure following happens:
- if concurrent invocation finds initialization (the
elsepart) happening, wait; other concurrent invocations go wait state. - if concurrent invocation finds initialization has happened (that file
/tmp/corners.txtpresent) loaded up.
i understood there several python interpreters running. don't use threads.
i solve file locking. there library: https://pypi.python.org/pypi/lockfile
example:
from lockfile import lockfile lock = lockfile("/some/file/or/other") lock: print lock.path, 'is locked.'
Comments
Post a Comment