SHARE
TWEET

Untitled

a guest Dec 8th, 2019 78 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import multiprocessing
  2. import traceback
  3. from timeit import default_timer as timer
  4. import random
  5.  
  6.  
  7. class ReaderProcess(multiprocessing.Process):
  8.     def __init__(self, filename, value):
  9.         multiprocessing.Process.__init__(self)
  10.         self.filename = filename
  11.         self.val = value
  12.  
  13.     def run(self):
  14.         self.read_data()
  15.  
  16.     def read_data(self):
  17.         start = timer()
  18.         try:
  19.             with open(self.filename, "r") as f:
  20.                 a = f.read()
  21.         except Exception:
  22.             traceback.print_exc()
  23.  
  24.         self.val.value = timer() - start
  25.         print(self.val.value)
  26.  
  27.  
  28. class WriterProcess(multiprocessing.Process):
  29.     def __init__(self, filename):
  30.         multiprocessing.Process.__init__(self)
  31.         self.filename = filename
  32.  
  33.     def run(self):
  34.         self.write_data()
  35.  
  36.     def write_data(self):
  37.         try:
  38.             with open(self.filename , 'a+', encoding="utf-8") as f:
  39.                 f.write("AAAAAAAAAA\n" * random.randint(40, 60))
  40.         except Exception:
  41.             traceback.print_exc()
  42.  
  43.  
  44. if __name__ == "__main__":
  45.     iteration = 0
  46.     queue = [[WriterProcess(str(i) + ".txt") for i in range(3)] for i in range(4)]
  47.     val = multiprocessing.Value('d')
  48.     times = [0.0, 0.0, 0.0]
  49.     for j in range(1, 4):
  50.         queue[j][j-1] = ReaderProcess(str(j-1) + ".txt", val)
  51.     file_to_read = 0
  52.     while True:
  53.         iteration += 1
  54.         cur = queue.pop(0)
  55.         for process in cur:
  56.             process.start()
  57.         for process in cur:
  58.             process.join()
  59.         times[file_to_read] = float(val.value)
  60.         if iteration >= 4:
  61.             queue.append([WriterProcess(str(i) + ".txt") for i in range(3)])
  62.             prets = times[:]
  63.             prets[file_to_read] = float('inf')
  64.             file_to_read = prets.index(min(prets))
  65.             queue[-1][file_to_read] = ReaderProcess(str(file_to_read) + ".txt", val)
  66.         else:
  67.             file_to_read = iteration % 3
  68.         print(iteration)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Not a member of Pastebin yet?
Sign Up, it unlocks many cool features!
 
Top