Guest User

semaphore, event, lock

a guest
Mar 12th, 2012
70
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. __author__ = 'user'
  2. import multiprocessing
  3. from time import sleep
  4.  
  5. class A:
  6.     def __init__(self, num_proc=4):
  7.         self.m = multiprocessing.Manager()
  8.         self.tasks_done = self.m.list()
  9.  
  10.         self.q = multiprocessing.Queue()
  11.  
  12.         self.num_proc = num_proc
  13.         #self.eve = multiprocessing.Event()
  14.         #self.sema = multiprocessing.Semaphore()
  15.         self.lo = multiprocessing.Lock()
  16.  
  17.     def worker(self):
  18.         while True:
  19.             #self.eve.wait()
  20.             #self.sema.acquire()
  21.             self.lo.acquire()
  22.  
  23.             task = self.q.get()
  24.             print task
  25.  
  26.             self.tasks_done.append(task)
  27.  
  28.             for i in range(task-5, task+5):
  29.                 if i not in self.tasks_done:
  30.                     self.add_task(i)
  31.  
  32.  
  33.             #self.eve.clear()
  34.             #self.sema.release()
  35.             self.lo.release()
  36.  
  37.  
  38.     def init_processes(self):
  39.         for i in range(self.num_proc):
  40.             p = multiprocessing.Process(target=self.worker)
  41.             p.daemon = True
  42.             p.start()
  43.         p.join()
  44.  
  45.     def add_task(self, i):
  46.         self.q.put(i)
  47.         #self.eve.set()
  48.  
  49.  
  50.  
  51. if __name__ == '__main__':
  52.     a = A()
  53.     a.add_task(100)
  54.     a.init_processes()
RAW Paste Data