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:

  1. if concurrent invocation finds initialization (the else part) happening, wait; other concurrent invocations go wait state.
  2. if concurrent invocation finds initialization has happened (that file /tmp/corners.txt present) 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

Popular posts from this blog

1111. appearing after print sequence - php -

java - WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/board/] in DispatcherServlet with name 'appServlet' -

Ruby on Rails, ActiveRecord, Postgres, UTF-8 and ASCII-8BIT encodings -