Showing posts with label 【PYTHON】multiprocessing. Show all posts
Showing posts with label 【PYTHON】multiprocessing. Show all posts

Tuesday, June 1, 2021

【PYTHON】multiprocessing

 from concurrent.futures import ProcessPoolExecutor

from concurrent.futures.thread import ThreadPoolExecutor
def occupy(x):
  count = x
  for i in range(11000):
    count += i
  return count


# it will only work if run in the name == main block
if __name__ == "__main__":
  print('.submit method for multiprocessing')
  jobs = []
  with ProcessPoolExecutor() as executor:
    for i in range(4):
      job = executor.submit(occupy, i)
      jobs.append(job)

  for job in jobs:
    print(job.result())

    print('.map method for multiprocessing')        
    # or, you can do it this way
    with ProcessPoolExecutor() as executor:
      results = [r for r in executor.map(occupy, range(4))]

    print(results)


    print('threading demo')
    jobs = []
    with ThreadPoolExecutor() as executor:
      for i in range(4):
        job = executor.submit(occupy, i)
        jobs.append(job)

    for job in jobs:
      print(job.result())

How to Launch a D2C Startup?

Discover why successful D2C startups validate identity before building products and how paid pilots can prove demand before an MVP exists...