You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

77 lines
1.5 KiB

  1. import time
  2. import random
  3. from multiprocessing import Process, Queue, current_process, freeze_support
  4. #
  5. # Function run by worker processes
  6. #
  7. def worker(input, output):
  8. for func, args in iter(input.get, 'STOP'):
  9. result = calculate(func, args)
  10. output.put(result)
  11. #
  12. # Function used to calculate result
  13. #
  14. def calculate(func, args):
  15. result = func(*args)
  16. return '%s says that %s%s = %s' % \
  17. (current_process().name, func.__name__, args, result)
  18. #
  19. # Functions referenced by tasks
  20. #
  21. def mul(a, b):
  22. time.sleep(0.5*random.random())
  23. return a * b
  24. def plus(a, b):
  25. time.sleep(0.5*random.random())
  26. return a + b
  27. #
  28. #
  29. #
  30. def test():
  31. NUMBER_OF_PROCESSES = 4
  32. TASKS1 = [(mul, (i, 7)) for i in range(20)]
  33. TASKS2 = [(plus, (i, 8)) for i in range(10)]
  34. # Create queues
  35. task_queue = Queue()
  36. done_queue = Queue()
  37. # Submit tasks
  38. for task in TASKS1:
  39. task_queue.put(task)
  40. # Start worker processes
  41. for i in range(NUMBER_OF_PROCESSES):
  42. Process(target=worker, args=(task_queue, done_queue)).start()
  43. # Get and print results
  44. print('Unordered results:')
  45. for i in range(len(TASKS1)):
  46. print('\t', done_queue.get())
  47. # Add more tasks using `put()`
  48. for task in TASKS2:
  49. task_queue.put(task)
  50. # Get and print some more results
  51. for i in range(len(TASKS2)):
  52. print('\t', done_queue.get())
  53. # Tell child processes to stop
  54. for i in range(NUMBER_OF_PROCESSES):
  55. task_queue.put('STOP')
  56. if __name__ == '__main__':
  57. freeze_support()
  58. test()