Navigation

    MakerGram Logo

    MakerGram

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Popular
    • Tags
    • Users
    • Groups

    Multi Thread Handling for normal Processes using python

    Raspberry Pi
    3
    7
    1850
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • kowshik1729
      kowshik1729 last edited by

      Hello all,
      I would like to know whether we can handle two different processes using python? like how our usual OS's do. For instance, I am using raspberry pi for reading video frames and at the same instance I'm handling a function where I am playing audio on speaker. Can I do both the things at the same time using two different individual threads on raspberry pi?

      If yes, please suggest me how can I achieve this. Thanks in advance..!!

      1 Reply Last reply Reply Quote 0
      • J
        jerinisready last edited by jerinisready

        I suggest you multiprocessing to handle dlifferent processes.
        Use multiprocessing.Process.
        If you want to establish a communication between parent and child process, use multiprocessing.Queue or multiprocessing.Pipe

        1 Reply Last reply Reply Quote 0
        • kowshik1729
          kowshik1729 last edited by

          @jerinisready Thank you soo much. Is Multiprocessing.process is an python library? Can i get it through PIP installer?

          J 1 Reply Last reply Reply Quote 0
          • salmanfaris
            salmanfaris last edited by

            Hi @kowshik1729 ,

            Yes, you can do Multi Thread in Raspberry Pi using python and note that different threads do not actually execute at the same time: they merely appear to.

            We can easily implement simple threads using threading module. I'll show you some example of how actually it works.

            Example :
            I was trying to blink two LED's at the same time, for that I created a function that does the blink infinitely using while(True) .

            import RPi.GPIO as GPIO
            import time
            
            Rled = 12
            Bled = 6
            
            GPIO.setmode(GPIO.BCM)
            
            GPIO.setup(Rled,GPIO.OUT)
            GPIO.setup(Bled,GPIO.OUT)
            
            
            def blue():
                    while True:
                            print "LED BLUE is  ON"
                            GPIO.output(Bled,GPIO.LOW)
                            time.sleep(1)
                            print "LED BLUE is  OFF"
                            GPIO.output(Bled,GPIO.HIGH)
                            time.sleep(1)
            def red():
                    while True:
                            print "LED RED is  ON"
                            GPIO.output(Rled,GPIO.LOW)
                            time.sleep(1)
                            print "LED RED is OFF"
                            GPIO.output(Rled,GPIO.HIGH)
                            time.sleep(1)
            
            blue()
            red()
            
            

            Output :

            Capture.PNG

            Video : https://www.youtube.com/watch?v=AypMEQFpEWo&feature=youtu.be

            since we are using the infinity loop for both methods, the blue() will not stop and red() will not invoke either.

            In these scenarios, we can use multithread both function without waiting for another , let's try.

            import RPi.GPIO as GPIO
            import time
            import threading
            
            
            
            Rled = 12
            Bled = 6
            
            GPIO.setmode(GPIO.BCM)
            
            GPIO.setup(Rled,GPIO.OUT)
            GPIO.setup(Bled,GPIO.OUT)
            
            
            def blue():
                    while True:
                            print "LED BLUE is  ON"
                            GPIO.output(Bled,GPIO.LOW)
                            time.sleep(1)
                            print "LED BLUE is  OFF"
                            GPIO.output(Bled,GPIO.HIGH)
                            time.sleep(1)
            def red():
                    while True:
                            print "LED RED is  ON"
                            GPIO.output(Rled,GPIO.LOW)
                            time.sleep(1)
                            print "LED RED is OFF"
                            GPIO.output(Rled,GPIO.HIGH)
                            time.sleep(1)
            
            
            t1 = threading.Thread(target=blue)
            t2 = threading.Thread(target=red)
            
            
            t1.start()
            t2.start()
            
            

            Output :

            Capture2.PNG

            Video : https://www.youtube.com/watch?v=HMKYzgdNwd8&feature=youtu.be

            with the help threading module we can simply run both methods at the same time (how we feel).

            I think you got your answer. also, keep in mind to avoid race condition and deadlock while multithreading.

            1 Reply Last reply Reply Quote 2
            • J
              jerinisready @kowshik1729 last edited by jerinisready

              @kowshik1729
              that's builtin at python. only thing is. you can simply import using

              from multiprocessing import Process
              def my_function_to_run(*args, **kwargs):
                   ...
                   ...
              
              def main():
                  p1 = Process(
                                 target=my_function_to_run, 
                                 args=('arg_01', 'arg_02', 'arg_03', ), 
                                 kwargs={'key': 'value', 'another_key':True}
                  )
                  p1.start()
                  p2 = Process(
                                 target=my_function_to_run, 
                                 args=('arg_01', 'arg_02', 'arg_03', ), 
                                 kwargs={'key': 'value', 'another_key':True}       
                  )
                  p2.start()
                  
                  p1.join()
                  p2.join()
                  print("Finished!")
              
              if __name__ == '__main__':
                 main()
              

              This Might can help: https://docs.python.org/2/library/multiprocessing.html

              1 Reply Last reply Reply Quote 1
              • kowshik1729
                kowshik1729 last edited by

                @salmanfaris Thankyou soo much for awesome example. The video really helped me what it looks like without multi threading. Thank you.

                salmanfaris 1 Reply Last reply Reply Quote 1
                • salmanfaris
                  salmanfaris @kowshik1729 last edited by salmanfaris

                  @kowshik1729 happy hacking and keep making.
                  all the best 😊 👍

                  1 Reply Last reply Reply Quote 0
                  • First post
                    Last post

                  Recent Posts

                  • @Suhailjr But I think since it's not a plug and plug play system and it will laying on the PCB for the long term, it might be fine. for me, it's similar to the Intel Edison and the PICO-IMX7 System-on-Module

                    dade502a-71f6-4da0-bd7d-0e9a0b602cb0-image.png

                    a4b8898f-90d4-4a34-ba5d-81ab76fda904-image.png

                    • read more
                  • @salmanfaris at last they update their design. T
                    What you think on the updated connector. I felt like its more fragile and high chance for corottion issue due to humidity for long term use.

                    • read more
                  • Built on the same 64-bit quad-core BCM2711 application processor as Raspberry Pi 4, Compute Module 4 delivers a step-change in performance over its predecessors: faster CPU cores, better multimedia, more interfacing capabilities, and, for the first time, a choice of RAM densities and a wireless connectivity option.

                    3094f292-3301-4364-a444-d828f6e77ff8-image.png

                    You can find detailed specs here,

                    1.5GHz quad-core 64-bit ARM Cortex-A72 CPU VideoCore VI graphics, supporting OpenGL ES 3.x 4Kp60 hardware decode of H.265 (HEVC) video 1080p60 hardware decode, and 1080p30 hardware encode of H.264 (AVC) video Dual HDMI interfaces, at resolutions up to 4K Single-lane PCI Express 2.0 interface Dual MIPI DSI display, and dual MIPI CSI-2 camera interfaces 1GB, 2GB, 4GB or 8GB LPDDR4-3200 SDRAM Optional 8GB, 16GB or 32GB eMMC Flash storage Optional 2.4GHz and 5GHz IEEE 802.11b/g/n/ac wireless LAN and Bluetooth 5.0 Gigabit Ethernet PHY with IEEE 1588 support 28 GPIO pins, with up to 6 × UART, 6 × I2C and 5 × SPI

                    31354fad-6332-40e8-b324-53e0aa5dbace-image.png

                    Compute Module 4 IO Board
                    89a3b68b-bb74-4002-9c2b-d32c2e1450b3-image.png

                    The IO board provides:

                    Two full-size HDMI ports Gigabit Ethernet jack Two USB 2.0 ports MicroSD card socket (only for use with Lite, no-eMMC Compute Module 4 variants) PCI Express Gen 2 x1 socket HAT footprint with 40-pin GPIO connector and PoE header 12V input via barrel jack (supports up to 26V if PCIe unused) Camera and display FPC connectors Real-time clock with battery backup

                    More details:
                    https://www.raspberrypi.org/products/compute-module-4/?variant=raspberry-pi-cm4001000, https://www.raspberrypi.org/blog/raspberry-pi-compute-module-4/

                    • read more
                  • https://www.dexterindustries.com/howto/run-a-program-on-your-raspberry-pi-at-startup/

                    This link has even more extensive ways to do it

                    • read more
                  • Hi @Akhil I found the following answer in one of the forums. here is the link to the thread.

                    The way that I've seen most people do it (have a look on the Raspberry Pi forums), and have done myself with success is using /etc/rc.local.

                    All you need to do here is put ./myscript in the rc.local text file. If it's in python, put python myscript.py.

                    This literally is "a simple solution, (like dropping my script in some "startup" directory or something similar)"- maybe search on the forums when you're having questions as well, this solution came up on the first 4 results of a google search!

                    • read more
                  By MakerGram | A XiStart Initiative | Built with ♥ NodeBB
                  Copyright © 2020 MakerGram, All rights reserved.
                  Privacy Policy | Terms & Conditions | Disclaimer | Code of Conduct