Page 1 of 1

running two functions simultaneously

Posted: Wed Mar 06, 2019 2:32 pm
by halajamal
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

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 2:42 pm
by B.Goode

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 2:42 pm
by rpiMike
It would help if you at least included some code to explain what you want to execute and what you want to test for.

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 2:59 pm
by jahboater
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.

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 3:11 pm
by halajamal
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.

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 3:12 pm
by halajamal
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

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 3:15 pm
by halajamal
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?

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 3:16 pm
by B.Goode
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.

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 3:43 pm
by Andyroo
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

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 3:47 pm
by bholland84
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

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 4:19 pm
by pfletch101
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).

Re: running two functions simultaneously

Posted: Wed Mar 06, 2019 4:30 pm
by halajamal
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

Re: running two functions simultaneously

Posted: Sun Mar 10, 2019 12:49 pm
by Andyroo
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.

Re: running two functions simultaneously

Posted: Sun Mar 10, 2019 3:37 pm
by Idahowalker
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.

Re: running two functions simultaneously

Posted: Sun Mar 17, 2019 7:30 pm
by mikerr
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)

Re: running two functions simultaneously

Posted: Thu Mar 21, 2019 11:31 am
by billbarren
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

Re: running two functions simultaneously

Posted: Thu Mar 21, 2019 9:06 pm
by Idahowalker
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