Updating a file using random access
As explained above, each thread tries to read and increment the value on the last line.This is set up so that we can track multiple threads interfering with each other. Before it increments the value to 21 and writes it back, another thread might come in and read the same value, 20. So if multiple values are found in the output file, it means multiple threads interfered with each other in updating the shared resource.If you do not exercise proper care, it is possible that inconsistent values are read and/or propagated. One solution to manage access to a shared resource across threads is to use a lock.A thread must acquire the lock before accessing a shared resource.Let us examine how this works with regard to reading and writing a file from multiple threads.We have an application with multiple worker threads, each of which need to read and update a file. Read Bytes(Rec Size) 'No positionng required ' Process the B array Loop '... The processing for that type of file would involve reading a byte at a time, assembling the byte array, until the Eo R marker is detected. Close() The other possibility is that the records are separated by a record marker.
And here is the main part of the program to create and start multiple threads to run the function above.Random access file processing involves positioning the file pointer to an absolute position within the file, and then reading data from that file position. The data is typically organised as fixed length records (and can often be read as a single structure), but random file access is also required for some variable length record structures, where the file position of a record is maintained in an index or as part of a linked list of records. And, this type of random errors are what makes these errors hard to track down.Let us now update the task worker function to obtain a lock before performing any other operations ( 1 else 'counter.txt' # re-initialize file with open(fname, 'w') as f: f.write('0\n') threads =  for i in xrange(0, 50): t = threading.