Python multiprocessing question! (Correction)

Asked 2 years ago, Updated 2 years ago, 106 views

After defining the class called Test, define the write and read functions in it After creating the object, I tried to run both functions at the same time using the multiprocessing module, and I tried coding to make sure that I used the self variables well! Therefore, the expected result is output from 0 to 20 and terminated. However, nothing happens on the console. Why is that? (win10 and python==3.6))

import time
from multiprocessing import Process


class Test:
    def __init__(self):
        self.queue = []
        self.end = 0

    def write(self):
        for i in range(20):
            self.queue.append((i, i+1) #Add data to queue
            # Modify the end value so that it can be broken after the input is completed until the end
            if i == 19:
                self.end = 1    


    def read(self):
        while True:
            if not self.queue: # Sleep for 1 second if queue is empty
                time.sleep(1)   
            else:
                ans = self.queue.pop(0) #Reads when data is present in the queue
                print(ans[1]) 
           # If there is no data in the queue and the end value is 1, exit
            if not self.queue and self.end == 1: 
                break


if __name__ == '__main__':
    tester = Test() #ObjectCreation

    p1 = Process (target=testter.write, args=()) #writeProcess
    p1.start()

    p2 = Process (target=testter.read, args=()) #readprocess
    p2.start()

    p1.join()
    p2.join()

python multiprocessing

2022-09-22 19:27

1 Answers

It's not multi-threaded, it's multi-processed.

The questioner's key question is that he wants to share the contents with two notepads easily.

In modern operating systems, processes can be viewed as isolated spaces.

The memory of Notepad A cannot be easily accessed from Notepad B.

In summary, if the above source was multi-threaded, you would have achieved the desired result. However, because it is a multi-process, it does not have access to (memory) between processes, so you do not get the expected results.

Then, how can data be exchanged and data (variables) shared?

Learn more about the IPC topic in the system programming book.

See link on Python.

If you analyze the assignment given in the document by using the shared memory provided by the multiprocessing module, you will get a sense.


2022-09-22 19:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.