This week you will experiment with running multiple processes at the same time.
p = Process(target=function_name, args=(yourargs,))to create the process, and p.start() to run the process. Note that process uses named arguments: you will always need to put "target=" before the function name, and "args=" before the arguments. Also note that the arguments are passed in as a tuple.
2. How many times will the code below print "Hello"?
def printAndSpawn(n): print("Hello") for i in range(n): p = Process(target=printAndSpawn, args=(n-1,)) p.start() p = Process(target=printAndSpawn, args=(3,)) p.start()
A process pool is a way to create a number of threads, and have them all do the same task. To create a pool of processes, where n is the number of processes you wish to create:
pool = Pool(processes=n)To run the processes, you will use the Pool.map function. The map function takes in a function, f, and a list of arguments, with the length of the list equal to the number of processes. (Essentially, you are handing in separate arguments for each process, in the form of a list. Note that this means your function will need to take a single argument, although that argument can be a list or a tuple.) It returns a list of the return values from the processes. This will look like:
results = pool.map(f, args_array)
5. Assume you have multiple processes using the same account to add and withdraw money. Which sections of code will you need to protect in order to not allow multiple processes to modify the same variable at once?