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
2 Answers
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()