0

I get a error when I run this code.

from multiprocessing import Process, cpu_count import time def counter(num): count = 0 while count < num: count += 1 def main(): print("cpu count:", cpu_count()) a = Process(target=counter, args=(500000000,)) b = Process(target=counter, args=(500000000,)) a.start() b.start() print("processing...") a.join() b.join() print("Done!") print("finished in:", time.perf_counter(), "seconds") main() 

I was expecting Python to print up to 1000000000 but it just gives me a unexpected error. I am not sure what if name == "main": does so I have not used it.

6
  • 1
    "I am not sure what if __name__ == "__main__": does so I have not used it." Removing that would be the first problem :) See also Compulsory usage of if __name__=="__main__" in windows while using multiprocessing and linked questions. Commented Jul 22, 2023 at 0:34
  • removing what?? Commented Jul 22, 2023 at 0:37
  • 2
    but it just gives me a unexpected error Are we supposed to guess what the error is? Commented Jul 22, 2023 at 0:37
  • @SkrugNuggsta the if __name__ == "__main__": guard. Commented Jul 22, 2023 at 0:37
  • if name == 'main': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable. Commented Jul 22, 2023 at 0:42

2 Answers 2

2

Your problem is that you must write:

if __name__ == '__main__': main() 

On non-Linux machines, Python starts new processes but having them re-read the main file. In your original code, each time a new process is started, it starts up another ten processes.

You need to make sure that main() is only executed once.

Sign up to request clarification or add additional context in comments.

1 Comment

"On non-Linux machines, Python starts new processes" fun fact, that fact this this isn't the default on unix systems is now considered a mistake. Current sites are on making spawn the default start method on unix systems as well in Python 3.14.
1

If you want to measure a duration you need to note both start and end times then subtract one from the other.

Something like this:

from multiprocessing import Pool from time import perf_counter def counter(num): for _ in range(num): ... return num N = 500000000 NPROCS = 2 def main(): start = perf_counter() with Pool() as pool: for ar in [pool.apply_async(counter, (N,)) for _ in range(NPROCS)]: print(ar.get()) end = perf_counter() print(f'Duration {end-start:.2f}s') if __name__ == '__main__': main() 

Output:

500000000 500000000 Duration 8.61s 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.