0

how can i dynamically change the value of lis so that every second it'll output a list in which the last element is 2x the last element of the previous list .

import time, multiprocessing

lis = [1, 2, 4]

def printer():
    while True:
        print(lis)
        time.sleep(1)

def updater():
    while True:
        time.sleep(1)
        lis.append(lis[-1]*2)

if __name__ == '__main__':
    process1 = multiprocessing.Process(target=updater)
    process2 = multiprocessing.Process(target=printer)

    process1.start()
    process2.start()

    process1.join()
    process2.join()

i need the output to be something like this

[1, 2, 4]
[1, 2, 4, 8]
[1, 2, 4. 8. 16]
[1, 2, 4, 8, 16, 32] 
.
.

but right now the output is

[1, 2, 4]
[1, 2, 4]
[1, 2, 4]
[1, 2, 4] 
.
.

I tried using global lis but that didnt work either.

2
  • 2
    You need to use multithreading, not multiprocessing. Each process has its own memory. Commented Jan 28, 2023 at 20:51
  • @Barmar actually there is a way to share information between processes. You can read more about it here: docs.python.org/3/library/… Commented Jan 28, 2023 at 21:13

1 Answer 1

2

You can achieve desired behavior using multiprocessing.Manager.

Managers provide a way to create data which can be shared between different processes. You can read more about it here.

Based on example from Server process section you can rewrite your code like this:

import time, multiprocessing


def printer(_lis):
    while True:
        print(_lis)
        time.sleep(1)

def updater(_lis):
    while True:
        time.sleep(1)
        _lis.append(_lis[-1]*2)

if __name__ == '__main__':
    with multiprocessing.Manager() as manager:
        lis = manager.list([1, 2, 4])
        process1 = multiprocessing.Process(target=updater, args=(lis,))
        process2 = multiprocessing.Process(target=printer, args=(lis,))

        process1.start()
        process2.start()

        process1.join()
        process2.join()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.