Xiao
Xiao

Reputation: 12725

Python error "I/O operation on closed file" when using a file handle with thread lock

I am trying to write to one file using Python threading module and I am already using the lock to access the file. the class like below:

  class WriteToFile(threading.Thread):
      def __init__(self,lock,fp):
          threading.Thread.__init__(self)
          self.lock=lock
          self.fp=fp
      def run():
          self.lock.acquire()
          self.fp.write('some string')
          self.lock.release()
  f=open('somefile','a')
  lock=threading.Lock()
  thread= WriteToFile(lock,f)
  thread.start()

Above code could only keep running for some time, and stoped due to ValueError: I/O operation on closed file

But if I access the file between the 'lock acquire and release' block instead of using a file handle, code could run without error. But that way is not good as every thread will open the file and close it.

Any explanation why? I am using Python 2.7.3 and Windows 7.

Upvotes: 2

Views: 4151

Answers (2)

Xiao
Xiao

Reputation: 12725

I added below code to to the end of the code to wait all child threads to finish and then close the file. And now it works.

  while threading.activeCount() >1:
      pass
  else:
      print 'All done!'
      f.close()

Upvotes: 2

Sergey Vedernikov
Sergey Vedernikov

Reputation: 7754

May be main thread is dead before write is called? I have tried your code with this addition at the end of script:

import time
time.sleep(1)

And it works.

Upvotes: 0

Related Questions