Advertisement
BlueManCZ

Untitled

Mar 21st, 2018
338
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.68 KB | None | 0 0
  1. import random
  2. import time
  3. from multiprocessing import Process, Manager, Value, Barrier, Semaphore
  4. from math import gcd
  5.  
  6. prvni = Value('i', -1)
  7. druhy = Value('i', -1)
  8. soudelna = Value('i', -1)
  9.  
  10. empty_buff1 = Semaphore(1)
  11. empty_buff2 = Semaphore(1)
  12. full_buff1 = Semaphore(1)
  13. full_buff1.acquire()
  14. full_buff2 = Semaphore(1)
  15.  
  16. onecount = Value('i', 0)
  17. totalcount = Value('i', 0)
  18. totalcount2 = Value('i', 0)
  19.  
  20. globallock = Value('i', 1)
  21.  
  22.  
  23. def producent():
  24.     while globallock.value:
  25.         empty_buff1.acquire()
  26.         prvni.value = random.randint(0, 1000000)
  27.         druhy.value = random.randint(0, 1000000)
  28.         full_buff1.release()
  29.  
  30.  
  31. def prod_konz():
  32.     while globallock.value:
  33.         full_buff1.acquire()
  34.         empty_buff2.acquire()
  35.         if gcd(prvni.value, druhy.value) > 1:
  36.             soudelna.value = 1
  37.         else:
  38.             soudelna.value = 0
  39.         totalcount2.value += 1
  40.         empty_buff1.release()
  41.         full_buff2.release()
  42.  
  43.  
  44. def konzument():
  45.     while globallock.value:
  46.         full_buff2.acquire()
  47.         if soudelna.value == 1:
  48.             onecount.value += 1
  49.         totalcount.value += 1
  50.         if totalcount.value >= N:
  51.             globallock.value = 0
  52.         empty_buff2.release()
  53.  
  54.  
  55. if __name__ == "__main__":
  56.     manager = Manager()
  57.  
  58.     N = 1000
  59.  
  60.     processes = []
  61.     functions = [producent, prod_konz, konzument]
  62.     starttime = time.time()
  63.     for i in functions:
  64.         p = Process(target=i)
  65.         processes.append(p)
  66.         p.start()
  67.  
  68.     for p in processes:
  69.         p.join()
  70.  
  71.     print(onecount.value/totalcount.value)
  72.     print(totalcount.value, totalcount2.value)
  73.     print(time.time()-starttime)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement