Multi Thread Handling for normal Processes using python



  • 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..!!



  • 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



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



  • 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.



  • @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



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



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


Log in to reply
 

Recent Posts

  • Very much informative!!!!

    read more
  • If you are using raspberry pi as one of your main computers and have separate monitor, keyboard and mouse, then you might be tired of copy and pasting terminal commands and codes while doing projects with raspberry pi, because running chromium-browser and reading tutorial will pi slower and using a sperate keyboard and mouse use our workbench space too.

    recently I read a blog Share your keyboard and mouse between computers with Barrier by Gordon Hollingworth which is cool.

    In that blog, he mentioned a software called barrier, it's a software that will allow you to use a single keyboard and mouse to control multiple computers by physically turning a dial on the box to switch the machine you're controlling at any given moment. The barrier does this in software, allowing you to tell it which machine to control by moving your mouse to the edge of the screen, or by using a keypress to switch focus to a different system.

    Follow these to share your computer keyboard and mouse with the raspberry pi

    First, we need setup raspberry pi

    Step 1: Download and Install Raspberry Pi OS on SD Card

    Step 2: Connect raspberry pi to the wi-fi network

    Step 3: Install barrier, for that open your terminal (Ctrl + T) and paste or enter the following

    sudo apt install barrier

    Then click enter.

    Step 4: Setup barrier, Open barrier by typing barrier on the terminal, if you successfully installed the barrier you can see like this.

    2020-07-02_19-54.png

    Select option Client (Use another computer's mouse and keyboard) and Select Auto config option too, also note the Screen name, which we need for the server.

    That's all next we need to set up the desktop/laptop computer.

    Step 5: Download and Install barrier on desktop or laptop computer (The Server), download link

    Step 6: Set up the barrier by selecting Server and position your monitor on barrier software. 004.png

    To Position, the screen clicks the configure server.

    005.png

    Here, to drag and drop the monitor icon to the desired position you need on the grid.

    007.png

    double click the screen and set the screen name, you can obtain the screen name from the raspberry pi barrier client. (See Step 4)

    008.png

    after setup, it should be like this. Then click OK

    2020-07-02_13-05.png

    in the following screen, click Apply and Just wait few seconds then try to move the mouse to the corner. Yes, It should work.

    read more
  • @rafitc99 Looks cool, Thanks for sharing. 👍

    read more
  • This is a speaker call for MakerChat by MakerGram. MakerChat is a webinar series where makers from different domain sharing their expertise with other fellow makers. MakerGram is an Open Community Platform for Makers and hardware enthusiasts to empower them by promoting learning, sharing and collaboration.

    Link: https://forms.gle/R5qhEhQeEe7UnJey9

    photo_2020-06-28_09-45-12.jpg

    Link: https://forms.gle/R5qhEhQeEe7UnJey9

    read more
  • The Challenge

    Do you think you can come up with some interesting ideas revolving around Amazon Alexa? What if we could help you build that idea into a reality. Tell us about your idea and the best one wins an Amazon Alexa Echo Dot.

    🧲 Bonus points for those solutions involving Covid-19 or promoting social-distancing.

    Schedule🗓

    Application - The application starts on 26th June 2020. Closing - The registration will end on 17th July 2020. Results - The results declared by last week of July

    For Registration: https://alexa.hackclub.com/

    AlexaChallenge

    read more