0

I have a file onto which I have written some data. Say 8 bytes of data Now using my python script, I want to read the first four bytes using one thread and the next 4 bytes using another thread while the first thread is still running or suspended. How can I do this using python? i.e 1) Read first 4 bytes using thread1 from file1 2) while thread1 running or suspended, read next 4 bytes from file1 using thread2

1
  • This sounds like a bad idea. Wouldn't it be easier to have only one thread read from the file and then hand off the data to workers to process? Commented Oct 24, 2012 at 16:23

2 Answers 2

3

Run two threads and open and read file separately in both threads, you can use seek to jump to specific positions

Sign up to request clarification or add additional context in comments.

Comments

0
from multiprocessing import Process, Queue

class MyFileWrapper:

    def __init__(self, filePath, start, stop):
        self.filePath = filePath
        self.start = start
        self.stop = stop

    def getData(self):
        with open(self.filePath, 'r') as f:
            f.seek(self.start)
            data = f.read(self.stop - self.start)
            print data

def worker(q):
    myFileWrapper = q.get()
    myFileWrapper.getData()

if __name__ == "__main__":

    work_queue = Queue()

    p1 = Process(target=worker, args=(work_queue,))
    p1.start()
    p2 = Process(target=worker, args=(work_queue,))
    p2.start()

    work_queue.put(MyFileWrapper('C:\Users\Asus\Desktop\pytest.txt', 0, 4))
    work_queue.put(MyFileWrapper('C:\Users\Asus\Desktop\pytest.txt', 4, 8))

    work_queue.close()
    work_queue.join_thread()
    p1.join()
    p2.join()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.