halajamal
Posts: 42
Joined: Wed Sep 26, 2018 11:36 am

running two functions simultaneously

Wed Mar 06, 2019 2:32 pm

Hi If i wanted to run two function at same time in python what should i use? For example Function to execute what i want and another checked if the executing is right or false


User avatar
rpiMike
Posts: 953
Joined: Fri Aug 10, 2012 12:38 pm
Location: Cumbria, UK

Re: running two functions simultaneously

Wed Mar 06, 2019 2:42 pm

It would help if you at least included some code to explain what you want to execute and what you want to test for.

jahboater
Posts: 4761
Joined: Wed Feb 04, 2015 6:38 pm

Re: running two functions simultaneously

Wed Mar 06, 2019 2:59 pm

halajamal wrote:
Wed Mar 06, 2019 2:32 pm
and another checked if the executing is right or false
This is very questionable.
While the other function is executing???
Why not just check the result in the same thread.

halajamal
Posts: 42
Joined: Wed Sep 26, 2018 11:36 am

Re: running two functions simultaneously

Wed Mar 06, 2019 3:11 pm

rpiMike wrote:
Wed Mar 06, 2019 2:42 pm
It would help if you at least included some code to explain what you want to execute and what you want to test for.
I am using a raspberry-pi with ultrasonic and IR sensor to detect and avoid obstacle
i have a distance that the car should travel to reach target . if it have an obstacle in its road then it will move until the sensor detect no obstacle then back to the origin path
by calculating how many distance it follow to avoid obstacle and what remaining distance to reach target.

halajamal
Posts: 42
Joined: Wed Sep 26, 2018 11:36 am

Re: running two functions simultaneously

Wed Mar 06, 2019 3:12 pm

B.Goode wrote:
Wed Mar 06, 2019 2:42 pm
threading?

https://docs.python.org/3/library/threading.html
Actually i was thinking about threading but don'y know how to implement

halajamal
Posts: 42
Joined: Wed Sep 26, 2018 11:36 am

Re: running two functions simultaneously

Wed Mar 06, 2019 3:15 pm

jahboater wrote:
Wed Mar 06, 2019 2:59 pm
halajamal wrote:
Wed Mar 06, 2019 2:32 pm
and another checked if the executing is right or false
This is very questionable.
While the other function is executing???
Why not just check the result in the same thread.
how's?

User avatar
B.Goode
Posts: 8833
Joined: Mon Sep 01, 2014 4:03 pm
Location: UK

Re: running two functions simultaneously

Wed Mar 06, 2019 3:16 pm

halajamal wrote:
Wed Mar 06, 2019 3:12 pm
B.Goode wrote:
Wed Mar 06, 2019 2:42 pm
threading?

https://docs.python.org/3/library/threading.html
Actually i was thinking about threading but don'y know how to implement


Try putting a search string similar to "python3 threading" into an internet search tool.

Andyroo

Re: running two functions simultaneously

Wed Mar 06, 2019 3:43 pm

This is a very simple thread example:

Code: Select all

from threading import Thread
import time

def run1():
    for x in range(5):
        print("Run 1 %s" % x)
        time.sleep(1)

def run2():
    for x in range(5):
        print("Run 2 %s" % x)
        time.sleep(2)

print("In main block")
t1 = Thread(target=run1)
threads = [t1]
t2 = Thread(target=run2)
threads += [t2]

t1.start()
t2.start()

for tloop in threads:
    tloop.join()

print("End of main block")
Functions run1 and run2 are the two background processes - these just print out who they are and a simple count
The main block set up a list of background functions in threads and then starts them
The for loop then joins them together so the main part of the program will not continue until ALL threads have completed

Feel free to hack this around - it was how I learnt the basics of threading from Google :D

bholland84
Posts: 10
Joined: Tue Mar 14, 2017 3:43 am

Re: running two functions simultaneously

Wed Mar 06, 2019 3:47 pm

Okay, so the real answer is that you can't. The GIL (global interpreter lock) will prevent exactly what you are trying to do. There are ways around this using multiple shells but let's just avoid that. BTW, this is the one area where python fails and the hacks to get around the GIL are really bad. That said, in every other language, you would use threading so the fake answer that will do what you want is to use threading.

Threading is quite simple to implement in python and there are lots of examples. The basic is that you are going to create a class that will extend the threading or Thread class, implements a run() method, and you now are running separate processes.

I wrote something up a while ago that does something similar with sensors.

https://github.com/bholland/PhotoProject

pfletch101
Posts: 527
Joined: Sat Feb 24, 2018 4:09 am
Location: Illinois, USA

Re: running two functions simultaneously

Wed Mar 06, 2019 4:19 pm

bholland84 wrote:
Wed Mar 06, 2019 3:47 pm
Okay, so the real answer is that you can't. The GIL (global interpreter lock) will prevent exactly what you are trying to do. There are ways around this using multiple shells but let's just avoid that. BTW, this is the one area where python fails and the hacks to get around the GIL are really bad. That said, in every other language, you would use threading so the fake answer that will do what you want is to use threading.
The GIL will prevent two threads in the same process from actually running at the same time, but threading works well if each thread does something and then needs to wait on I/O or sleep for a specified time before it does something else. If you really need interleaved execution of multiple active 'threads' within an application, you can use multiprocessing, the API for which is not a great deal more difficult to use than that for threading (at least in straightforward cases).

halajamal
Posts: 42
Joined: Wed Sep 26, 2018 11:36 am

Re: running two functions simultaneously

Wed Mar 06, 2019 4:30 pm

Andyroo wrote:
Wed Mar 06, 2019 3:43 pm
This is a very simple thread example:

Code: Select all

from threading import Thread
import time

def run1():
    for x in range(5):
        print("Run 1 %s" % x)
        time.sleep(1)

def run2():
    for x in range(5):
        print("Run 2 %s" % x)
        time.sleep(2)

print("In main block")
t1 = Thread(target=run1)
threads = [t1]
t2 = Thread(target=run2)
threads += [t2]

t1.start()
t2.start()

for tloop in threads:
    tloop.join()

print("End of main block")
Functions run1 and run2 are the two background processes - these just print out who they are and a simple count
The main block set up a list of background functions in threads and then starts them
The for loop then joins them together so the main part of the program will not continue until ALL threads have completed

Feel free to hack this around - it was how I learnt the basics of threading from Google :D
thank you very much
and if i have an interrupt?
can they stop to execute together?
and is there a possible interrupt in python but not keyboard type

Andyroo

Re: running two functions simultaneously

Sun Mar 10, 2019 12:49 pm

Apologies - just seen the follow up questions :oops:

If the interrupts are driven by the GPIO pins changing state, these can be picked up by the Python GPIO module and execute a bit of code.

If you need to stop the threads at the same time you would have to write a check into them for a value in a global variable being set. For example ‘if threadstop == True : break’ where threadstop is a global variable. This could be as a condition on the while loop or a function called to check if the end is required.

Idahowalker
Posts: 445
Joined: Wed Jan 03, 2018 5:43 pm

Re: running two functions simultaneously

Sun Mar 10, 2019 3:37 pm

Entering "python multiprocessing" will bring you closer to running two things, on the Pi at the 'same' time. The Python IDLE will NOT do multiprocessing, as of the last time I tried. Use Thonny for multiprocessing. You'll also need to use queues if passing info from one processor to the next.

Threading is just time slicing a program on one core. Multiprocessing is putting one function on one core and the other function on the other core. In the case of the Pi you'll have to still share core use with the OS but you'll be closer to 'at the same time' than with threading.
Without knowing why you are deleting my postings, I will not know how...

mikerr
Posts: 2781
Joined: Thu Jan 12, 2012 12:46 pm
Location: UK
Contact: Website

Re: running two functions simultaneously

Sun Mar 17, 2019 7:30 pm

Python multiprocessing is now very easy to use.

I used that in a practical way to ping the local subnet to discover all hosts:

https://github.com/mikerr/Pingu

Relevent part code is:

Code: Select all

def ping:
      ....

hosts = []       
for i in range(255):
      hosts.append("192.168.0." + str(i))

pool = ThreadPool(100)
results = pool.map(ping, hosts)
which simultaneously runs 100 copies of the ping function at a time, each with a unique host
(255 host entries total, so 2 batches of 100, then 55 - the map command sorts that out for you)
Android app - Raspi Card Imager - download and image SD cards - No PC required !

billbarren
Posts: 1
Joined: Thu Mar 21, 2019 11:29 am

Re: running two functions simultaneously

Thu Mar 21, 2019 11:31 am

halajamal wrote:
Wed Mar 06, 2019 3:12 pm
Actually i was thinking about threading but don'y know how to implement
Check this one...Python threading basics

Idahowalker
Posts: 445
Joined: Wed Jan 03, 2018 5:43 pm

Re: running two functions simultaneously

Thu Mar 21, 2019 9:06 pm

mikerr wrote:
Sun Mar 17, 2019 7:30 pm
Python multiprocessing is now very easy to use.

I used that in a practical way to ping the local subnet to discover all hosts:

https://github.com/mikerr/Pingu

Relevent part code is:

Code: Select all

def ping:
      ....

hosts = []       
for i in range(255):
      hosts.append("192.168.0." + str(i))

pool = ThreadPool(100)
results = pool.map(ping, hosts)
which simultaneously runs 100 copies of the ping function at a time, each with a unique host
(255 host entries total, so 2 batches of 100, then 55 - the map command sorts that out for you)
As a note. Multiprocessing is not the same as multithreading.
A bit of reading might help: https://www.quora.com/How-do-I-do-multi ... -in-Python
Without knowing why you are deleting my postings, I will not know how...

Return to “Python”