Advertisement
Guest User

Untitled

a guest
Dec 21st, 2014
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. """
  2. Process class can also be subclassed just like threading.Thread;
  3. Queue works like queue.Queue but for cross-process, not cross-thread
  4. """
  5. import os, time, queue
  6. from multiprocessing import Process, Queue # process-safe shared queue
  7. # queue is a pipe + locks/semas
  8. class Counter(Process):
  9. label = ' @'
  10.  
  11. def __init__(self, start, queue): # retain state for use in run
  12. self.state = start
  13. self.post = queue
  14. Process.__init__(self)
  15.  
  16. def run(self): # run in newprocess on start()
  17. for i in range(3):
  18. time.sleep(1)
  19. self.state += 1
  20. print(self.label, self.pid, self.state) # self.pid is this child's pid
  21. self.post.put([self.pid, self.state]) # stdout file is shared by all
  22. print(self.label, self.pid, '-')
  23.  
  24.  
  25. if __name__ == '__main__':
  26. print('start', os.getpid())
  27. expected = 9
  28. post = Queue()
  29. p = Counter(0, post) # start 3 processes sharing queue
  30. q = Counter(100, post) # children are producers
  31. r = Counter(1000, post)
  32. p.start()
  33. q.start()
  34. r.start()
  35. while expected: # parent consumes data on queue
  36. print('left------------>', expected)
  37. time.sleep(0.5) # this is essentially like a GUI,
  38. try: # though GUIs often use threads
  39. data = post.get(block=False)
  40. except queue.Empty:
  41. print('no data...')
  42. else:
  43. print('posted:', data)
  44. expected -= 1
  45. p.join()
  46. q.join()
  47. r.join() # must get before join putter
  48. print('finish', os.getpid(), r.exitcode) # exitcode is child exit status
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement