proc2.py 864 B

1234567891011121314151617181920212223242526272829303132
  1. #!/usr/bin/env python
  2. from multiprocessing import Pool
  3. import os
  4. import time
  5. import random
  6. def worker(data):
  7. print "[%s] starting process, working on [%s]" % (os.getpid(), data)
  8. time.sleep(random.randrange(5))
  9. success = (random.random() > 0.2)
  10. if success:
  11. print "[%s] finished [%s] successfully" % (os.getpid(), data)
  12. else:
  13. print "[%s] error processing [%s]" % (os.getpid(), data)
  14. return success
  15. if __name__ == '__main__':
  16. mydata = ["the", "quick", "brown", "fox", "jumped",
  17. "over", "the", "lazy", "dog"]
  18. p = Pool(4) # defaults to number of CPUS
  19. # can also provide an initialization function
  20. # and arguments to it
  21. print "[%s] Pool created" % os.getpid()
  22. results = p.map(worker, mydata)
  23. print "[%s] Pool map completed" % os.getpid()
  24. print results