Python Multiprocessing Tutorial: Run Code in Parallel Using the Multiprocessing Module

Поделиться
HTML-код
  • Опубликовано: 2 окт 2024
  • In this video, we will be learning how to use multiprocessing in Python.
    This video is sponsored by Brilliant. Go to brilliant.org/cms to sign up for free. Be one of the first 200 people to sign up with this link and get 20% off your premium subscription.
    In this Python Programming video, we will be learning how to run code in parallel using the multiprocessing module. We will also look at how to process multiple high-resolution images at the same time using a ProcessPoolExecutor from the concurrent.futures module. Let's get started...
    The code from this video can be found at:
    bit.ly/multipro...
    Threading Tutorial - • Python Threading Tutor...
    List Comprehensions Tutorial - • Python Tutorial: Compr...
    Exception Handling Tutorial - • Python Tutorial: Using...
    Pillow (PIL) Tutorial - • Python Tutorial: Image...
    ✅ Support My Channel Through Patreon:
    / coreyms
    ✅ Become a Channel Member:
    / @coreyms
    ✅ One-Time Contribution Through PayPal:
    goo.gl/649HFY
    ✅ Cryptocurrency Donations:
    Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3
    Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33
    Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot
    ✅ Corey's Public Amazon Wishlist
    a.co/inIyro1
    ✅ Equipment I Use and Books I Recommend:
    www.amazon.com...
    ▶️ You Can Find Me On:
    My Website - coreyms.com/
    My Second Channel - / coreymschafer
    Facebook - / coreymschafer
    Twitter - / coreymschafer
    Instagram - / coreymschafer
    #Python

Комментарии • 939

  • @coreyms
    @coreyms  5 лет назад +465

    Hey everybody! I hope you find this video helpful. I'm finally moved into my new home, so I should be back on a schedule of regular releases very soon. Hope everyone has a great weekend!

    • @deadfool6105
      @deadfool6105 5 лет назад +9

      Please make a video on asyncio too..

    • @param8378
      @param8378 5 лет назад

      @@deadfool6105 yes yes

    • @beastgenv
      @beastgenv 5 лет назад +1

      Congrats on the move

    • @wizard-28
      @wizard-28 5 лет назад

      Corey, can you make jupyter notebooks on these tutorials also. By the way congratulations!

    • @admintest9291
      @admintest9291 5 лет назад +1

      Bless you man!

  • @anhurtjv
    @anhurtjv 3 года назад +12

    I just started an internship in Germany and you have no idea how helpful these classes series are to young people like me that want to succeed in the professional world of today :)

  • @shawnalexander5704
    @shawnalexander5704 4 года назад +11

    Of all the resources out there that I have looked to get a start and grasp on this subject (some cost money), this video is on point!

    • @erik-martin
      @erik-martin 4 года назад

      Corey's channel has done more for me in 2 weeks than any other resource I have tried over the last 10 years.

  • @neolithian
    @neolithian 5 лет назад +22

    We need at least a dozen of Corey Schafer in our programming learning life. I wish everyone would follow your method. You are simply the best! God bless.

  • @tebbythomas1809
    @tebbythomas1809 5 лет назад +24

    Another wonderful video. Thanks to your videos I've gained an understanding of how to build and deploy a Django web application, using matplotlib for data visualisations, python multi-threading, python-multiprocessing, exception handling, python unit test cases and more. Your content is consistently excellent because of how practical and well thought out your videos are. Extremely useful! Please keep making these videos! Thanks a lot! You're helping a lot of people with this high quality content!

  • @jordanbyrne4628
    @jordanbyrne4628 3 года назад +2

    Just came here to say thanks for this. I just completed my first ever paid work programming, made a simple image slicing and joining script. Client mentioned he wanted it to run though 20000 images in under an hour after I built a demo. I rebuilt it using concurrent.futures and your video saved me hours of work! Plus it runs super quick. Thanks so much!

    • @drygordspellweaver8761
      @drygordspellweaver8761 2 года назад

      Curious how much something like this pays? I wrote a similar but much more complex script for myself recently

  • @nikitapetrenko1236
    @nikitapetrenko1236 2 года назад +1

    Even these years, this video is really informative about that topic

  • @aadityalolariya2751
    @aadityalolariya2751 2 года назад +1

    Absolutely amazing video. Well if anybody is getting any error for the same code as in the video then use the main function in your code. I had encountered it (don't know why)...

  • @wylde780
    @wylde780 5 лет назад +6

    Nice work with the real world example not only does it help the learning process after the foundation has been laid. It also encourages thought on personal projects that will help you apply this new-found knowledge.

  • @vincent.borreux
    @vincent.borreux Год назад +2

    I struggle a bit to run this trivial pgm on my venv python 3.11.1. Ultimately, this one has run properly ... Thanks a lot anyway for this tutorial, which I definitely like a lot ! Hope this helps:
    import time
    from multiprocessing import Process
    start = time.perf_counter()
    def do_something(seconds=1):
    print(f'Sleeping {seconds} second(s)...')
    time.sleep(seconds)
    return f'Done Sleeping...{seconds}'
    if __name__ == '__main__':

    p1 = Process(target=do_something, args=[2])
    p2 = Process(target=do_something, args=[3])
    p1.start()
    print(f"Process 1 pid {p1.pid}")

    p2.start()
    print(f"Process 2 pid {p2.pid}")

    p1.join()
    p2.join()
    finish = time.perf_counter()
    print(f'Finished in {round(finish-start, 2)} second(s)')

  • @vicstan5983
    @vicstan5983 5 лет назад +779

    Why do people give thumbs down to someone who teaches for free? And a small detail ... the man is a grandmaster! Thank you sir for doing this. Greetings from the Netherlands

    • @bartekz88
      @bartekz88 4 года назад +52

      There are jealous because they're programming in Cobol.

    • @darwinvinci7744
      @darwinvinci7744 4 года назад +68

      I think it's the Australians. You see, they have everything upside down there, when they thumbs up, it's thumbs down for us. Corey is the best.

    • @Bubelaschka
      @Bubelaschka 4 года назад +16

      I think it's some kind of obsessive compulsive disorder.

    • @josephsagotti8786
      @josephsagotti8786 4 года назад +3

      ~0.78% of people who voted, thumbed down down.

    • @kyleyoung4974
      @kyleyoung4974 4 года назад +6

      .. because its not working for them.. so they wasted their time getting 'taught' something that didn't work. .hence thumbs down.

  • @SaiSai-gs3pd
    @SaiSai-gs3pd 3 года назад

    Have never understood multithreading and multiprocessing this clearly ever before in my life. Would greatly appreciate if you can post a video on locks. Deadlock and livelock and how to resolve them. Thanks for the service you are doing to so many people.

  • @gytisbl
    @gytisbl Год назад +28

    31:12 Mr. Schafer finishes with the theory and goes into the real-world example with processing images
    35:37 implementing multi-processing to single thread/process operation
    40:04 easy switch from Processes to Threads
    Love Your videos Mr. Schafer. Especially Your communication skills. No BS, just clear communication. I also love that You don't edit out mistakes, and summarize after several steps. Thank You for putting the effort and sharing.

  • @user-he4ef9br7z
    @user-he4ef9br7z 4 года назад

    thanks man , you are a savior , after watching your videos on multiprocessing and threading i could finally make a project i wanted to make for a long time - python which counts the number of times i press each key and store them in an excel file for each day

  • @SHA256HASH
    @SHA256HASH 4 года назад +9

    This is the second video I've watched from your channel and was blown away at the quality of the content and the clarity of the concepts explained. Once I get into a data analyst role, I will support you on Patreon. Until then, I will watch every other video! 😁Thanks a million!

    • @coreyms
      @coreyms  4 года назад +4

      Thanks! That helps more than you know. I really appreciate it!

  • @mikenesbitt8052
    @mikenesbitt8052 2 года назад

    Wow!! I kind of understood multi processing, but this polished up everything I know into a very sparkly vision.... Thank you!!!

  • @nadik4531
    @nadik4531 4 года назад +8

    Brah i was stuck at work tryna do this. Searched your name and braaaah! Your videos are so helpful.

  • @awndlr
    @awndlr 5 лет назад +5

    thx so much, already implemented that into my webscraping scripts and the speed gain is tremendous. you’re explaining this so well an clear. thx a lot.

    • @sellosejake
      @sellosejake 4 года назад

      Hear trying to achieve the same

  • @ginadi9733
    @ginadi9733 4 года назад +60

    There are courses that take thousands of dollars for teaching what you're teaching. you're teaching very well and you give it free.
    Respect.

  • @siddiksalim5037
    @siddiksalim5037 3 года назад

    I came to this video with a working knowledge of python threads, processes and asynchronous coroutines.
    I must say, this video was very well-executed. It helped me arrange my own thoughts on the matter, and I think anyone new
    to the concept of multiprocessing would find Corey's explanation easy to understand.
    I also commend his insistence on showing a practical example, as it helps a lot of people bring new concepts into perspective.
    Congratulations on a job well done!

    • @drygordspellweaver8761
      @drygordspellweaver8761 2 года назад

      Yeah sure you are a thread expert that’s why you watched a tutorial video.
      People and their cringey little egos... lmao 🤦‍♂️

  • @robertlee6529
    @robertlee6529 5 лет назад +342

    Just a reminder, on Windows you need to add "if __name__ == '__main__'"

    • @coreyms
      @coreyms  5 лет назад +63

      Thanks! I usually run my videos through my Windows laptop before posting just to make sure it's the same for both operating systems, but I didn't do that this time. I appreciate the comment!

    • @ThePasupathi
      @ThePasupathi 5 лет назад +9

      @@coreyms Somehow, me too facing errors without using main function. Even after using the if __name__ == '__main__', i got my output in different way .
      done sleeping 5 second(s).....
      done sleeping 4 second(s).....
      done sleeping 3 second(s).....
      done sleeping 2 second(s).....
      done sleeping 1 second(s).....
      sleeping 3 second(s)....
      sleeping 2 second(s)....
      sleeping 1 second(s)....
      sleeping 4 second(s)....
      sleeping 5 second(s)....
      Finished in 5.5 second(s)

    • @whoa_that_ruled
      @whoa_that_ruled 5 лет назад +16

      Just curious (python beginner), where would that go in the script?

    • @veganath
      @veganath 5 лет назад +71

      @@whoa_that_ruled
      import multiprocessing
      import time
      start = time.perf_counter()
      def do_something():
      print('Sleeping for 1 second')
      time.sleep(1)
      print('Done sleeping...')
      if ___name___ == '__main__':
      p1 = multiprocessing.Process(target=do_something)
      p2 = multiprocessing.Process(target=do_something)
      p1.start()
      p2.start()
      p1.join()
      p2.join()
      finish = time.perf_counter()
      print(f'Finished in {round(finish-start,4)} seconds')

    • @ahmedkhalil3015
      @ahmedkhalil3015 5 лет назад

      Add a shebang directive and you wouldn’t need one.

  • @javedalam7383
    @javedalam7383 2 года назад

    One of the best video of Multiprocessing I have ever seen. Thanks for all your effort and teaching us.

  • @ronnetgrazer362
    @ronnetgrazer362 5 лет назад +63

    It's one of those tutorials that has you reaching for the like button several times during the video, and once more after it's ended.

    • @krystianfeigenbaum238
      @krystianfeigenbaum238 3 года назад +12

      Well, then let's hope this urge posesses you an uneven number of times or it would be unfair to the author.

  • @shivstn98
    @shivstn98 5 лет назад +1

    The best instructor in the world... you explain tough things very easily... better than all others(including paid)
    Instructor 100%👌
    Content 100%👌
    Quality 100%👌
    Explanation 100%👌
    Thankyou so much ❤ keep inspiring us...

    • @coreyms
      @coreyms  5 лет назад +1

      Thanks!

    • @shivstn98
      @shivstn98 5 лет назад

      That's so humble you replied sir... sir can you please upload numpy and pandas tutorial

    • @manojk1494
      @manojk1494 Год назад

      @@shivstn98 I hope you already found that from his playlist, there are 11 videos for Pandas.

  • @snoopyjc
    @snoopyjc 5 лет назад +105

    Thanks Corey! Next please do async!!

    • @AnShett
      @AnShett 5 лет назад

      Yes, this is concept I haven't used but would really like to learn about.

    • @Skaxarrat
      @Skaxarrat 5 лет назад +6

      Yes please, async and when to use async/asyncio/threading/multiprocessing.

    • @user-be8ud2qd2d
      @user-be8ud2qd2d 5 лет назад

      Yes would strongly appreciate this

    • @folorunso
      @folorunso 4 года назад

      Yes, async will a perfect next. Thanks Corey for the handwork.

    • @ashfaquechowdhury1343
      @ashfaquechowdhury1343 4 года назад +1

      Yes please and then about locks,race conditions and queues as well. Thanks a lot.Loved your explanation.

  • @scholar_sukhiya
    @scholar_sukhiya 4 года назад +2

    thanks a lot Mr Schafer!! your videos helps me a lot, plus the tips u give to keep the code clean are making my projects look awesome

  • @vipuljoshi7367
    @vipuljoshi7367 4 года назад +91

    31 people didn't find a piece of code they could copy and paste for their work.

  • @Wallaby1010101
    @Wallaby1010101 2 года назад

    This video was a great introduction for a Python newbie like myself, with previous experience using a Future API in R.

  • @chinpokomon_
    @chinpokomon_ 4 года назад +134

    the longest deja vu in my life so far

  • @yuzhu2547
    @yuzhu2547 3 года назад

    You're a grandmaster. I really appreciate you put all stuff in ONE video. So easy to navigate. Thank you!

  • @raghav-cx3qq
    @raghav-cx3qq 4 года назад +18

    I am not in a position right now to donate through patreon. All I can do is watch your videos without skipping ads and give it a like.

    • @coreyms
      @coreyms  4 года назад +3

      That helps a ton too! Thanks!

  • @nikhileshsaggere
    @nikhileshsaggere Год назад

    Excellent tutorials, he teaches practical concepts with zero assumptions on the background and makes sure he gives real life examples and practical code to get you through! Brilliant 🙏🏻

  • @johntamplin
    @johntamplin 4 года назад +3

    When faced with a python challenge, I ask myself "What would Corey Schafer do?" I then, somewhat ironically, ask myself "Why am I wasting my time asking myself rhetorical questions, when I could be watching one of his outstanding videos."

  • @MrEliyahilel
    @MrEliyahilel 3 года назад

    My python classes knowledge came from you and now multiprocessing/threading. Thanks a lot for AMAZING content!

  • @eduardolpz386
    @eduardolpz386 4 года назад +38

    Great video!
    If you are running this in Windows and a later version of Python (I'm running 3.7), you need to run all multiprocessing under main(), then run if __name__ == '__main__': main()
    Make sure the do_something() function is declared outside main().

    • @yoyoliyang
      @yoyoliyang 4 года назад +1

      current

    • @caseymcmahan4834
      @caseymcmahan4834 2 года назад

      Thank you! Just the fix I was looking for. This is apparently true of macs as well

    • @Svkenapps
      @Svkenapps 2 года назад

      You fixed my Programm🤝

    • @drygordspellweaver8761
      @drygordspellweaver8761 2 года назад

      Only the code that spawns the subprocess needs to be guarded.

    • @thomasmayne2629
      @thomasmayne2629 2 года назад

      thank you so mutch

  • @tsolakisgeo
    @tsolakisgeo 3 года назад

    I had to make an index by checking 150,000 numbers over 110,000 entries:
    Before Multiprocessing: 3558 seconds
    After Multiprocessing: 115 seconds
    Many, many thanks!

  • @spacecowboy2483
    @spacecowboy2483 Год назад +7

    This video is gold, every second of it. You are very talented at teaching complex concepts, you can't even begin to fathom how much I appreciate your work. Thanks!

  • @KrzysztofSpikowski
    @KrzysztofSpikowski 3 года назад

    best explanation ever, I was really stuck when studying multiprocessing on coursera, could not get my head around, now is all crystal clear, thanks Corey

  • @khmsalhuas1
    @khmsalhuas1 5 лет назад +7

    Dude you are amazing! Excellent excellent stuff! Truly great educator and we own you a lot.
    I have a question. What if my function takes more than one argument. Will the ProcessPoolExecutor instance (executor) be able to map the function to however number of arguments for every process?

    • @drygordspellweaver8761
      @drygordspellweaver8761 2 года назад

      It’s the map method that would handle that. The function then would naturally need to accept multiple arguments

  • @viswanathbarenkala1023
    @viswanathbarenkala1023 2 года назад

    Thanks for all the info Schafer, its a great work for community. Was checking this code if the code is not put in main this is giving error. Writing here so that you can edit for any future users. Once again thank you for all the great work and sharing it for free. Also you narration is great and I am tuned to it.

  • @gerhardboenisch5618
    @gerhardboenisch5618 4 года назад +6

    I had to add
    if __name__ == '__main__':
    for it to work in Python 3.7.6
    I did not get the print output, but the images were processed

    • @XinhLe
      @XinhLe 3 года назад

      The same for me!
      def main():
      if __name__ == "__main__":
      main()
      and it worked, anyone can help to explain why?

  • @thomaswilliams5599
    @thomaswilliams5599 Год назад

    This has helped me take a task that usually takes 3 hours, down to 30 minutes. Thank you! Best thing I ever did was watch these

  • @attilagyen1446
    @attilagyen1446 4 года назад +35

    In newer versions of Python instead of using a list in args you should use tuple. So instead of writing this args=[1.5] write this args=(1.5,). It's okay to use the list version, but you will get a warning. Good tutorial btw.

    • @salfredogonzal_
      @salfredogonzal_ 2 года назад +2

      Not anymore ...
      self = reduction.pickle.load(from_parent)
      AttributeError: Can't get attribute ...

  • @abhi.c137
    @abhi.c137 2 года назад

    Excellent hands-on walkthrough of Python with lots of examples. Thank you, appreciate your video!

  • @piiumlkj6497
    @piiumlkj6497 5 лет назад +5

    Any computer vision tutorial coming ? Would be awesome !

  • @phoenix6909
    @phoenix6909 Год назад

    Amazing master!!! just love the way you walk through !!!! thanks you serrrrr

  • @SebaSalinas91
    @SebaSalinas91 5 лет назад +6

    Thank you so much for this quality of videos on Python!... Cant tell you how much i`ve learned with them. Keep it coming! :D
    PS. Any GUI tutorials coming?
    PS2. Greetings from Chile!

  • @BhanudaySharma506
    @BhanudaySharma506 4 года назад

    Man... You have explained so good.... Fall in love with your teaching style.

  • @sebastianbarriap.6871
    @sebastianbarriap.6871 5 лет назад +7

    Excelent tutorial!, just for completeness, i'd love to see some tutorial on python coroutines, thanks a lot.

  • @biswajit-k
    @biswajit-k Год назад +1

    Thanks, Corey! Great Tutorial

  • @IrshadKhan-vk8rn
    @IrshadKhan-vk8rn 5 лет назад +5

    Thnx sir I got placed in a MNC all bcz of you learned python a lot and still learning a lot whenever I have any doubts stack overflow and you r my mentor thnx again preparing for higher studies now..

    • @venkatkumar8672
      @venkatkumar8672 5 лет назад

      i pursuing a college degree and I'm learning python in different resources and i learned the basics , will you please recommend me a good resource for mastering python language and to go to next level??

  • @geoffcounihan7093
    @geoffcounihan7093 4 года назад +1

    You're vids are gems

  • @nguyennguyenkhoi9988
    @nguyennguyenkhoi9988 Год назад +3

    when i watch your vidieos i belive that if you can't explain something easy to understand, absolutely nobody on this world can do that. thanks you alot Corey, you make my life easier.

  • @shariqahmad8994
    @shariqahmad8994 4 года назад +1

    Thanks you Sir ...for all your amazing videos . Your explanation are very clear.You are great teacher . Thanks for the enormous amount of hard work to make the videos.

  • @9SMTM6
    @9SMTM6 5 лет назад +8

    The reason it finished the 1s future in the Multiprocessing part after the 2 and (just after) the 3s future is that the PoolExecutor limited the threads to 4 (you said yourself that it chooses the number of concurrent threads based i.e. your hardware). And your list of times to wait is reversed in duration. So it only started the future for the 1s duration AFTER the first future finished, the one with a duration of 2s. So the 1s future finished after 2+1= 3s plus overhead, so slightly after the 3s future.
    Edit: Aaand you realized that just shortly after. Was wondering why noone else wrote this before.

    • @drygordspellweaver8761
      @drygordspellweaver8761 2 года назад

      No one mentioned it because it’s literally spelled out in the video 🤦‍♂️

    • @9SMTM6
      @9SMTM6 2 года назад

      @@drygordspellweaver8761 I did wait some time to write that comment.
      You meanwhile were too lazy to read my whole comment.

    • @drygordspellweaver8761
      @drygordspellweaver8761 2 года назад

      @@9SMTM6 Literally everyone who watched the video understood what was going on. Only you saw fit to go out of your way to write a comment to "explain" what was literally explained in the video like 5 seconds after it happened. You are insufferably arrogant and dense.

  • @elyon2966
    @elyon2966 2 года назад

    You are a real real giga chad for providind this for free !

  • @thedrei24
    @thedrei24 5 лет назад +6

    oh man, you don't even know how long I was looking for a video on multiprocessing.

  • @VarunKumar-yg8ij
    @VarunKumar-yg8ij 2 года назад

    Thanks A Ton for this Brilliant Video !! Really one of the best explanation !!

  • @kylebaker8502
    @kylebaker8502 3 года назад +4

    Hi Corey, great video covered a lot, one thing I was hoping to see here which I did not was using Pool from Multiprocessing to pass multiple parameters to a class or function. I ended up finding it after some digging using starmap with zip instead of map. To pass constants with this method import itertools and use the repeat inside the zip. Hope this helps anyone looking for this.

  • @pav8369
    @pav8369 3 года назад

    This Video is great! especially that you've shown dynamic processes and the rl example THANKS!

  • @edwardwong654
    @edwardwong654 Год назад +3

    Corey is great. When you help people, and I mean really HELP people, he is just a saint. I am on Python 3.9.12 and my code does not execute properly, even though I am copying verbatim and I a stuck at the 10:20 mark. After I put in the p1/p2.start() statements, the script runs without printing the "sleep" statements. The final print statement does execute.
    But after I put in the p1/p2.join() statements, I get a runtime error:
    An attempt has been made to start a new process before the
    current process has finished its bootstrapping phase.
    This probably means that you are not using fork to start your
    child processes and you have forgotten to use the proper idiom
    in the main module:
    if __name__ == '__main__':
    freeze_support()
    ...

  • @ManoelBarrionuevo
    @ManoelBarrionuevo 3 года назад +1

    Boy, how I miss a "love" reaction on youtube. It would be great to have it here right now. Great video! This helped me a lot. :D

  • @dhurda471
    @dhurda471 2 года назад +4

    This has been incredibly helpful for me and my team. I'm a network engineer working on multiprocessing SSH connections and this made everything make sense. Definitely subscribed after seeing this.

  • @tarunkathula8819
    @tarunkathula8819 3 года назад

    Thank you very very much.
    your explanation was very good and very detailed.
    This video helped me a lot.

  • @anuprshetty6391
    @anuprshetty6391 2 года назад +3

    Hi Sir,
    As you mentioned, I am interested to learn advanced threading concepts like race condition, mocks, etc. Please make videos on that too. I will be waiting... Between really nice video. Thanks for the effort.

  • @liesk666
    @liesk666 3 года назад

    This an excellent tutorial. Thanks a lot your pedagogy and the quality of your video

  • @hongbingqin6876
    @hongbingqin6876 5 лет назад +3

    It's great video. However, I receive the following error when run your code to print results in my windows. But the code works when I run it in aws environment.
    BrokenProcessPool Traceback (most recent call last)
    in
    3 results = executor.map(do_something, secs)
    4
    ----> 5 for result in results:
    6 print(result)
    7
    ~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\process.py in _chain_from_iterable_of_lists(iterable)
    474 careful not to keep references to yielded objects.
    475 """
    --> 476 for element in iterable:
    477 element.reverse()
    478 while element:
    ~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in result_iterator()
    584 # Careful not to keep a reference to the popped future
    585 if timeout is None:
    --> 586 yield fs.pop().result()
    587 else:
    588 yield fs.pop().result(end_time - time.monotonic())
    ~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in result(self, timeout)
    430 raise CancelledError()
    431 elif self._state == FINISHED:
    --> 432 return self.__get_result()
    433 else:
    434 raise TimeoutError()
    ~\AppData\Local\Continuum\anaconda3\lib\concurrent\futures\_base.py in __get_result(self)
    382 def __get_result(self):
    383 if self._exception:
    --> 384 raise self._exception
    385 else:
    386 return self._result
    BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.

    • @surajitchakraborty1903
      @surajitchakraborty1903 4 года назад +2

      @Hongbing , even I am getting the same error in windows. Did you manage to get around it - if so then how ?

    • @darkfantasy437
      @darkfantasy437 4 года назад

      @@surajitchakraborty1903 I'm getting similar errors in pycharm - not exactly the same, but similar (also on windows)

  • @MohammedBakheet
    @MohammedBakheet 4 года назад +1

    You are the best, thank you so much for the clear explanation, keep it up

  • @hacker2ish
    @hacker2ish 5 лет назад +3

    You could have put the image processing and the reading and writing from disk in separate functions you could have used threads for the IO and procesess for the processing

  • @sananazari4797
    @sananazari4797 4 года назад +1

    Thank you. This was very much useful

  • @world_of_hein
    @world_of_hein 4 года назад +3

    @Corey Schafer,
    Thank you very much for taking the time to make this video. I have written my first-ever parallelized code and the speedup is invaluable.
    For years I was apprehensive about learning parallelization methods because they seemed very complicated. You, my friend, have opened the flood gates. This work puts me one step closer to completing my Master's.

  • @luciusbennet2120
    @luciusbennet2120 3 года назад

    Just a correction. Tasks can be CPU-bound, IO-bound and Memory-bound. In last type the bottleneck are the systems surrounding memory access, most likely the bus itself. Matrix manipulation (likely img manipulation too) is a kind of memory-bound task, not cpu-bound. Computing pi is cpu-bound , for example

  • @bigbangdata
    @bigbangdata 4 года назад +8

    Thanks for the smooth and didactic intro to multiprocessing, I've done this a year ago during a fast and furious degree and needed a refresher. I have a case in which this will come in handy although it's hundreds of lines of code, but I bet I can wrap them all into a function to be the executor's target.

    • @drygordspellweaver8761
      @drygordspellweaver8761 2 года назад

      A function with hundreds of lines might not be such a good idea lol. Try learning Classes and Methods and I’m sure you can incorporate multiprocessing in a much more encapsulated way

    • @bigbangdata
      @bigbangdata 2 года назад +1

      @@drygordspellweaver8761 right you are, god knows what insanity I was up to 2 years ago.

    • @drygordspellweaver8761
      @drygordspellweaver8761 2 года назад

      @@bigbangdata haha must have been a blast

  • @poke_champ
    @poke_champ 5 лет назад +1

    You are my favorite channel for python I always learn something new! Will you also try to do other languages as well? Wondering about your road map.

  • @vincenzo3574
    @vincenzo3574 5 лет назад +3

    What's the difference between time.perf_counter() and time.time()? Why should I use one over the other?

    • @TheOiish
      @TheOiish 5 лет назад +2

      The resolution of perf_counter() is higher than that of time().

    • @Mayur7Garg
      @Mayur7Garg 5 лет назад +1

      But he is eventually rounding off😅

  • @M10PrasanthkmCR7
    @M10PrasanthkmCR7 4 месяца назад

    Thank you man, saved my day! hats off...always gratefull

  • @guardrepresenter5099
    @guardrepresenter5099 4 года назад +4

    for i inrange(1,1000000):
    print ("Thank you")

    • @jimmy2643
      @jimmy2643 4 года назад +4

      print("Thank you
      "*1000000)
      # :)

    • @sebastianjost
      @sebastianjost 4 года назад +1

      @@jimmy2643 wow. I didn't know this was possible... thank you!

  • @GamingGirlfriend_
    @GamingGirlfriend_ 5 месяцев назад

    Thnak you for the tutorial. It was really helpful!

  • @MrRobbi373
    @MrRobbi373 5 лет назад +7

    That's the module I used to parallelize and optimize Mosaik smart grid co-simulations in my bachelor's thesis, which I finished this week! :D

  • @ananay22
    @ananay22 4 года назад

    The reason the map printed them in order is, because the list you mapped them had them in the order of 5, 4, 3, 2, 1. The results were stored in the same index as that of the seconds, and when you printed them, you printed the result for 5, then 4 etc.

  • @yandere_lover-tl9zs
    @yandere_lover-tl9zs 4 года назад +5

    Bro, can you tell me why this error pops up?? I'm trying to print the return value of the function.
    concurrent.futures.process.BrokenProcessPool: A process in the process pool was terminated abruptly while the future was running or pending.

    • @concert_music
      @concert_music 4 года назад

      Very good video, though yes, this is really frustrating me too!

    • @TheEpicPineapple56
      @TheEpicPineapple56 4 года назад

      @@concert_music You have to encase your code in that
      > if ___name___ == "__main__":
      thing. This is done to avoid unwanted side effects, and multiprocessing and concurrent.futures libraries both force programmers (at least on Windows; Corey is on Mac) to do that. Hope that helps! :D

    • @lethalfang
      @lethalfang 4 года назад

      Took me a while to find the issue: stackoverflow.com/questions/61860800/running-a-processpoolexecutor-in-ipython
      Basically I added those lines on top when I'm using MacOS on jupyter-lab:
      import multiprocessing as mp
      mp.set_start_method('fork')

  • @ramarao_amara
    @ramarao_amara 5 лет назад +1

    Thanks bro, your teaching is really awesome ..

  • @unperrier5998
    @unperrier5998 2 года назад +4

    At 40:40 you're omitting one important thing: GaussianBlur() is an extension using a library written in C. So it can processing the image in a separately managed thread in C and relinquish execution to the python interpreter to process python bytecode on other python threads.
    So it's essentially a bad example, because at the low-level it behaves like multiprocessing in the sense that it can run things outside the python interpreter (multiprocessing does that in a separate process, PIL does that in a private thread, in C).
    So your assessment that the workload is I/O bound is incorrect. It is mostly CPU bound, but the processing you chose released the GIL, that's an unfortunate choice.

  • @jackrorystaunton4557
    @jackrorystaunton4557 4 года назад +2

    Corey could you do a tutorial demonstrating the SyncManager for sharing global variables across processes? This would be extremely helpful! Thanks for all your service, your videos are indispensable :)

    • @DevBishwasBh
      @DevBishwasBh 2 года назад

      Yeah, I am also seeking for that/.

  • @rakeshkumarkuwar6053
    @rakeshkumarkuwar6053 4 года назад +5

    Thank you, Corey, for such a wonderful explanation. The best part of this video is you have used the real-time problem, which helps to understand the concept in more depth.

  • @MrJalilMaqsood
    @MrJalilMaqsood 3 года назад

    Loved it. Great video with amazing way of communication.

  • @KirillBezzubkine
    @KirillBezzubkine 3 года назад

    Corey s channel s real treasure

  • @victor-ioncislari2375
    @victor-ioncislari2375 3 года назад

    Had a Problem with Image reading through PIL. I solved by using the following method:
    from PIL import Image
    import os
    my_path = os.path.dirname(__file__)
    files = os.listdir(my_path)
    I = Image.open(f'{my_path}/I1.jpg')
    I.show()
    Hope it helps and saves time.

  • @klyntonh7168
    @klyntonh7168 2 года назад

    Absolutely phenomenal video!! Thank you so much for doing this.

  • @saeedtajdini1038
    @saeedtajdini1038 Год назад

    Thank you, Corey, for this awesome tutorial. It was my intro to multiprocessing and I have already put it to practice to my benefit. I have one request if possible: please do an advanced version of this and explain chunksize, imap, imap_unordered, etc. I'm confused, e.g., it seems like with chunksize =1, map and imap_unordered behave in the same way. The documentation of this module is not great.

  • @mdmusaddique_cse7458
    @mdmusaddique_cse7458 7 месяцев назад

    Fantastic explanation!

  • @mariusj8542
    @mariusj8542 2 года назад +1

    Spot on!

  • @renatoaraujo6108
    @renatoaraujo6108 3 года назад +2

    Nice explanation about paralel processing! Thank you!
    Nice explanation about paralel processing! Thank you!
    Nice explanation about paralel processing! Thank you!
    Nice explanation about paralel processing! Thank you!
    Nice explanation about paralel processing! Thank you!

  • @meisamghasemi8635
    @meisamghasemi8635 17 дней назад

    Thanks a lot! So clear and handy.

  • @keweml3544
    @keweml3544 2 года назад

    This one is pretty good. Do you have a tutorial on multiprocessing with shared memory ?

  • @dasdunetechnologies1695
    @dasdunetechnologies1695 4 года назад

    Your Python tutorials are just great! Do you have anything about asyncio ?

  • @natylaza8220
    @natylaza8220 5 лет назад

    Thanks for your great videos with awesome explanations & examples!
    I learn from your videos a lot ! - from the beginning when I started learning python and now this wonderful videos which is "just in time" for me (threading & multiprocessing ).
    I'll definitely continue watch your videos ( Django Tutorial is next :) ) & recommend it!

  • @FRequena
    @FRequena 5 лет назад +1

    Thank you very much! It was nicely explained!

  • @omarsilva924
    @omarsilva924 5 лет назад +1

    Thank you. Excellent lesson

  • @MikeJans
    @MikeJans 5 лет назад +1

    Hey Corey, thanks again for a really great tutorial! First time i did understand multithreading ;-)