Jump to content
Sign in to follow this  
maomao2028

How to run a multi-process script

Recommended Posts

How to run a multi-process script as following by P4D:

 

from multiprocessing import Pool, TimeoutError
import time
import os
def f(x):
    return x*x
if __name__ == '__main__':
    # start 4 worker processes
    with Pool(processes=4) as pool:
        # print "[0, 1, 4,..., 81]"
        print(pool.map(f, range(10)))
        # print same numbers in arbitrary order
        for i in pool.imap_unordered(f, range(10)):
            print(i)
        # evaluate "f(20)" asynchronously
        res = pool.apply_async(f, (20,))      # runs in *only* one process
        print(res.get(timeout=1))             # prints "400"
        # evaluate "os.getpid()" asynchronously
        res = pool.apply_async(os.getpid, ()) # runs in *only* one process
        print(res.get(timeout=1))             # prints the PID of that process
        # launching multiple evaluations asynchronously *may* use more processes


        multiple_results = [pool.apply_async(os.getpid, ()) for i in range(4)]
        print([res.get(timeout=1) for res in multiple_results])
        # make a single worker sleep for 10 secs
        res = pool.apply_async(time.sleep, (10,))
        try:
            print(res.get(timeout=1))
        except TimeoutError:
            print("We lacked patience and got a multiprocessing.TimeoutError")
        print("For the moment, the pool remains available for more work")
    # exiting the 'with'-block has stopped the pool
    print("Now the pool is closed and no longer available")
 

Share this post


Link to post

It is a bit tricky to run multiprocessing from P4D.

 

For instance with Demo01:

- Set VenvPythonExe to the appropriate python.exe path e.g. 'c:\python\python313\python.exe'

- If you are printing from the processes and you want to see the output set UseWindowsConsole to True.  In your script there is no printing from the processes.

- Add to the above script as first statement:

__file__ = file_path

- Save your script to that filepath

- Run the demo and exec your script.

 

image.thumb.png.78a6cddf37c1c94a91f58f15fadb5f99.png

Share this post


Link to post
2 hours ago, maomao2028 said:

Great, it works.

 

Can the console window be hidden when the program is running?

 

Set UseWindowConsole to True and in the FormCreate add:

 

  ShowWindow(GetConsoleWindow, SW_HIDE);

 

Edited by pyscripter

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×