MakerGram Logo

    MakerGram

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

    Multi Thread Handling for normal Processes using python

    Raspberry Pi
    3
    7
    5326
    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

                  • Testing Raspberry Pi's Camera Module 3 (NEW for 2023)

                    • read more
                  • 1666287f-258d-437d-b2c5-91851d08617c-image.png
                    The classic compact camera for Raspberry Pi with a 12MP sensor and autofocus

                    Available from $25 with your choice of standard and wide lenses, with or without an infrared filter

                    bf34763e-5ba3-4962-8e92-75583fd1e96c-image.png

                    More details: https://www.raspberrypi.com/products/camera-module-3/

                    Raspberry Pi Camera Module 3 - Autofocus cameras!

                    Resource:
                    Documentation: https://www.raspberrypi.com/documentation/accessories/camera.html
                    Camera Software: https://www.raspberrypi.com/documentation/computers/camera_software.html

                    • read more
                  • Hey @rafitc99 ,

                    Did your issue resolve? Curious to know 😊

                    • read more
                  • @rafitc99 said in NMCLI AP Mode config error | Connection activation failed: No suitable device found for this connection | Raspberry Pi 3 Model B Rev 1.2:

                    host="MyRPiAPMode"
                    sudo nmcli con add type wifi ifname wlan0 con-name $host autoconnect yes ssid $host
                    sudo nmcli con modify $host 802-11-wireless.mode ap 802-11-wireless.band bg ipv4.method shared
                    sudo nmcli con modify $host wifi-sec.key-mgmt wpa-psk
                    sudo nmcli con modify $host wifi-sec.psk "SomeRandomPassword"
                    sudo nmcli radio wifi on
                    sudo nmcli con up $host

                    Hi @rafitc99, Are you able to set up the AP when trying the commands individually?

                    • read more
                  • I was trying to configure AP mode in Raspberrypi by using Network Manager. I'm using the below script. but it is throwing some errors.

                    Bash Script to set AP Mode

                    host="MyRPiAPMode" sudo nmcli con add type wifi ifname wlan0 con-name $host autoconnect yes ssid $host sudo nmcli con modify $host 802-11-wireless.mode ap 802-11-wireless.band bg ipv4.method shared sudo nmcli con modify $host wifi-sec.key-mgmt wpa-psk sudo nmcli con modify $host wifi-sec.psk "SomeRandomPassword" sudo nmcli radio wifi on sudo nmcli con up $host

                    Error ----

                    Connection 'MyRPiAPMode' (60965f2a-f510-48ef-afaf-0864242d0c06) successfully added. Error: Connection activation failed: No suitable device found for this connection (device eth0 not available because profile is not compatible with device (mismatching interface name)).

                    nmcli con (After script execution)

                    NAME UUID TYPE DEVICE Wired connection 1 9589ff1a-9923-3de3-a8a4-90b319661878 ethernet eth0 MyRPiAPMode 60965f2a-f510-48ef-afaf-0864242d0c06 wifi --

                    nmcli dev

                    DEVICE TYPE STATE CONNECTION eth0 ethernet connected Wired connection 1 wlan0 wifi unavailable -- lo loopback unmanaged --

                    I tried to make it availble via sudo nmcli radio wifi on
                    But not working.

                    this is the log

                    -- Journal begins at Sat 2021-08-07 09:28:21 IST. -- Aug 10 15:06:19 NWPI-b5b072 NetworkManager[16140]: <info> [1660124179.9816] audit: op="connection-update" uuid="60965f2a-f510-48ef-afaf-0864242d0c06" name="MyRPiAPMode" args="802-11-wireless-security.psk" pid=25120 uid=0 result="success" Aug 10 15:06:20 NWPI-b5b072 NetworkManager[16140]: <info> [1660124180.0902] audit: op="radio-control" arg="wireless-enabled" pid=25125 uid=0 result="success" Aug 10 15:06:21 NWPI-b5b072 NetworkManager[16140]: <info> [1660124181.4241] agent-manager: agent[641f99ab55d9691c,:1.692/nmcli-connect/0]: agent registered Aug 10 15:06:21 NWPI-b5b072 NetworkManager[16140]: <info> [1660124181.4281] audit: op="connection-activate" uuid="60965f2a-f510-48ef-afaf-0864242d0c06" name="MyRPiAPMode" result="fail" reason="No suitable device found for this connection (device eth0 not available because profile is not compatible with device (mismatching interface name))." Aug 10 15:06:52 NWPI-b5b072 NetworkManager[16140]: <info> [1660124212.0573] agent-manager: agent[70ee130ba0f26cd7,:1.696/nmcli-connect/1000]: agent registered Aug 10 15:06:52 NWPI-b5b072 NetworkManager[16140]: <info> [1660124212.0614] audit: op="connection-activate" uuid="60965f2a-f510-48ef-afaf-0864242d0c06" name="MyRPiAPMode" result="fail" reason="No suitable device found for this connection (device eth0 not available because profile is not compatible with device (mismatching interface name))." Aug 10 15:07:23 NWPI-b5b072 NetworkManager[16140]: <info> [1660124243.0370] agent-manager: agent[cc77ef461499c164,:1.700/nmcli-connect/0]: agent registered Aug 10 15:07:23 NWPI-b5b072 NetworkManager[16140]: <info> [1660124243.0414] audit: op="connection-activate" uuid="60965f2a-f510-48ef-afaf-0864242d0c06" name="MyRPiAPMode" result="fail" reason="No suitable device found for this connection (device eth0 not available because profile is not compatible with device (mismatching interface name))." Aug 10 15:07:41 NWPI-b5b072 NetworkManager[16140]: <info> [1660124261.8406] agent-manager: agent[79b01af218789b42,:1.702/nmcli-connect/0]: agent registered Aug 10 15:07:41 NWPI-b5b072 NetworkManager[16140]: <info> [1660124261.8446] audit: op="connection-activate" uuid="60965f2a-f510-48ef-afaf-0864242d0c06" name="MyRPiAPMode" result="fail" reason="No suitable device found for this connection (device eth0 not available because profile is not compatible with device (mismatching interface name))."

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