Roy Lee
Roy Lee

Reputation: 329

Is there any ways to execute multi while loops at the same time in Python?

I have several functions that read and write data from shared memory and they are executing by while loop.

For example,

def functionA():
    while True:
         # read data from shared memory
         # manipulate data and write again to shared memory

def functionB():
    while True:
         # read data from shared memory at the same time with functionA()
         # manipulate data (different way with functionA()) and write to shared memory(also different)

In this circumstance, How can I execute two functions in a main function?

I tried multiprocess as shown below

if __name__ == '__main__':
    A = Process(target=functionA)
    B = Process(target=functionB)
    A.start()
    B.start()
    A.join()
    B.join()

It does not work

Upvotes: 0

Views: 73

Answers (1)

Ofer Sadan
Ofer Sadan

Reputation: 11942

You can use threading in a very similar way:

from threading import Thread, Lock

And your lines have to change very little:

if __name__ == '__main__':
    A = Thread(target=functionA)
    B = Thread(target=functionB)
    A.start()
    B.start()
    A.join()
    B.join()

You should note however that it's not "thread-safe" to manipulate the same object in both threads at the same time without using some safer method, like a Lock (imported above). So your functions might have to change a little:

non_thread_safe_object = list() # Just an example
lock = Lock()

def functionA():
    while True:
        with lock:
            non_thread_safe_object.append('something')
        unrelated_code()

def functionB():
    while True:
        with lock:
            non_thread_safe_object.append('something else')
        other_unrelated_code()

Both of these can run at the same time because the lock makes sure only one unsafe action runs at any given time, while the other unrelated actions can happen whenever that code is encountered.

Also note that without breaking the loops (and using while True) both of these will run forever.

Upvotes: 2

Related Questions