Home Python: Multiple threads that can cross-communicate
Reply: 2

Python: Multiple threads that can cross-communicate

Calum
1#
Calum Published in 2018-01-12 12:46:10Z

I want to run two separate functions that loop at constant time intervals, that run at the same time.

Function1 needs to loop every 60 seconds. I then want to trigger the start of Function2 from Function1. Function2 then loops every 5 seconds. At a certain point I want to stop Function2.

What is the best solution for this? Thanks for any help.

Matias Cicero
2#
Matias Cicero Reply to 2018-01-12 13:18:38Z

You can easily do this using multiprocessing.Process:

from multiprocessing import Process

def function1():
    # ... Initiate loop
    child_process = Process(target=function2)
    child_process.daemon = True # We want function2 to be terminated if function1 exits for some reason
    child_process.start()
    # ... Continue loop execution as normal
    # ... After some time
    child_process.terminate() # This will terminate function2
    # ...
    return

def function2():
    # ... Loop and do stuff
    return

function1()

If you want to synchronize both processes, you can use a Lock:

from threading import Lock

global_lock = Lock()

def function1():
    child_process = Process(target=function2)
    child_process.daemon = True 
    child_process.start()
    with global_lock:
         # Lock acquired
         print('function1')
    # Lock released
def function2():
    with global_lock:
         # Lock acquired
         print('function2')
    # Lock released

function1()

With this approach you can guarantee that the print statements will never be executed in parallel, but rather sequentially

Will
3#
Will Reply to 2018-01-12 12:54:02Z

You can use a condition variable to signal from one thread to another thread.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.314735 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO