Async Techniques and Examples in Python Transcripts
Chapter: Leveraging CPU cores with multiprocessing
Lecture: Multiprocessing return values

Login or purchase this course to watch this video and the rest of the course contents.
0:00 So this multiprocessing is great if we're going to kick off a bunch of work and have it be done. What if we need an answer though?
0:08 What if we need to get back some kind of result from all of this work? How do we do that? It turns out multiprocessing has a pretty
0:15 good answer. Let's have a look. I'm going to call this a task here and what we're going to do is we can actually capture the return value of a variable
0:24 that we can put them all in to. I'm going to pin it like that and then when we're done, we can also print out our results.
0:37 We can go to these tasks and we say t.get() Notice we can pass a time out. It will let us know whether it's ready.
0:45 We can wait on it, we can know whether or not the response was actually successful. Like the execution was successful and so on.
0:51 I'm going to do a get() and we'll print that out. We're going to get, well, right now nothing back because do_math() returns nothing.
0:58 But let's try and make it do something interesting. So here we're generating a bunch of numbers. Let's go over here and have an average
1:07 set that to zero and let's say the value is that, so we'll say average going to add the value and we're going to divide by the number.
1:16 We want it to return, just make this an integer the average right there. This is not really a meaningful number
1:23 we're computing, but we're going to return that value from each block of the run that we're working with. Let's go ahead and run that, then I'm going
1:31 to go to something called the get() function. That will return the value, returned on line 40 there. Let's run it and see what happens.
1:38 Doing all the work like before and boom, look at that. Those are the answers. Here are our results. I got those back from the various
1:45 functions that ran. Of course we got them back in the order that we started them, not in the order in which they finished.
1:53 Because we start item one, put it in the list. Start item two, put it in the list and so on. Then we just, when everything's finished
2:02 we go through all the items first from the list second in the list and get the results. Correlate those back really clearly.
2:08 This is the first block, the second block and third block of data that we're working with. That's how you get results back or even
2:15 understand whether or not the operation was successful when using multiprocessing.

Talk Python's Mastodon Michael Kennedy's Mastodon