title: Python error "I/O operation on closed file" when using a file handle with thread lock
body: <p>I am trying to write to one file using Python <code>threading</code> module and I am already using the lock to access the file. the class like below:</p>
  
  <pre><code>  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()
  </code></pre>
  
  <p>Above code could only keep running for some time, and stoped due to <code>ValueError: I/O operation on closed file</code></p>
  
  <p>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.</p>
  
  <p>Any explanation why? I am using Python 2.7.3 and Windows 7.</p>