Hướng dẫn python stream data between processes - Python luồng dữ liệu giữa các quy trình

Tôi đang sử dụng đa xử lý để tạo một quy trình phụ cho ứng dụng Python của mình. Tôi muốn chia sẻ dữ liệu giữa quy trình cha mẹ của tôi và quy trình con. Điều quan trọng là phải đề cập rằng tôi cần chia sẻ điều này một cách không đồng bộ, có nghĩa là quy trình con và quy trình cha sẽ cập nhật dữ liệu trong quá trình chạy mã.

Điều gì sẽ là cách tốt nhất để thực hiện điều đó?

hỏi ngày 2 tháng 2 năm 2016 lúc 15:25Feb 2, 2016 at 15:25

Hướng dẫn python stream data between processes - Python luồng dữ liệu giữa các quy trình

2

Đây là một ví dụ đơn giản từ tài liệu Python -

from multiprocessing import Process, Queue

def f(q):
    q.put([42, None, 'hello'])

if __name__ == '__main__':
    q = Queue()
    p = Process(target=f, args=(q,))
    p.start()
    print q.get()    # prints "[42, None, 'hello']"
    p.join()

Bạn cũng có thể sử dụng đường ống, tham khảo để biết thêm chi tiết - https://docs.python.org/2/l Library/Multiprocessing.html

Đã trả lời ngày 2 tháng 2 năm 2016 lúc 15:36Feb 2, 2016 at 15:36

Hướng dẫn python stream data between processes - Python luồng dữ liệu giữa các quy trình

AlokthakuralokthakurAlokThakur

3,4791 Huy hiệu vàng18 Huy hiệu bạc32 Huy hiệu đồng1 gold badge18 silver badges32 bronze badges

4

Dưới đây là một ví dụ về Multiprocess-Multithread và chia sẻ một vài biến:

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 

Đã trả lời ngày 5 tháng 5 năm 2021 lúc 6:07May 5, 2021 at 6:07

Grantrgrantrgrantr

5147 Huy hiệu bạc14 Huy hiệu đồng7 silver badges14 bronze badges

Mã nguồn: lib/multiprocessing/shared_memory.py Lib/multiprocessing/shared_memory.py

Mới trong phiên bản 3.8.


Mô -đun này cung cấp một lớp,

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2, cho việc phân bổ và quản lý bộ nhớ chia sẻ được truy cập bởi một hoặc nhiều quy trình trên máy đa bộ xử lý đa lõi hoặc đối xứng (SMP). Để hỗ trợ quản lý vòng đời của bộ nhớ chia sẻ, đặc biệt là trong các quy trình riêng biệt, một lớp con
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
3,
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
4, cũng được cung cấp trong mô-đun
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
5.

Trong mô -đun này, bộ nhớ được chia sẻ đề cập đến các khối bộ nhớ được chia sẻ của hệ thống V System v (mặc dù không nhất thiết phải được triển khai rõ ràng như vậy) và không đề cập đến bộ nhớ chia sẻ phân tán. Kiểu bộ nhớ được chia sẻ này cho phép các quy trình riêng biệt có khả năng đọc và ghi vào một vùng chung (hoặc chia sẻ) của bộ nhớ dễ bay hơi. Các quy trình được giới hạn quy ước chỉ có quyền truy cập vào không gian bộ nhớ quy trình của riêng họ nhưng bộ nhớ được chia sẻ cho phép chia sẻ dữ liệu giữa các quy trình, tránh cần phải gửi tin nhắn giữa các quy trình chứa dữ liệu đó. Chia sẻ dữ liệu trực tiếp qua bộ nhớ có thể cung cấp các lợi ích hiệu suất đáng kể so với việc chia sẻ dữ liệu qua đĩa hoặc ổ cắm hoặc các thông tin liên lạc khác đòi hỏi phải tuần tự hóa/giải phóng hóa và sao chép dữ liệu.

ClassMultipRocessing.Shared_Memory.SharedMemory (name = none, created = false, size = 0) ¶multiprocessing.shared_memory.SharedMemory(name=None, create=False, size=0)

Tạo một khối bộ nhớ được chia sẻ mới hoặc gắn vào một khối bộ nhớ được chia sẻ hiện có. Mỗi khối bộ nhớ chia sẻ được gán một tên duy nhất. Theo cách này, một quy trình có thể tạo một khối bộ nhớ được chia sẻ với một tên cụ thể và một quy trình khác có thể gắn vào cùng một khối bộ nhớ được chia sẻ đó bằng cách sử dụng cùng tên đó.

Là một tài nguyên để chia sẻ dữ liệu trên các quy trình, các khối bộ nhớ được chia sẻ có thể vượt qua quy trình ban đầu tạo ra chúng. Khi một quy trình không còn cần truy cập vào khối bộ nhớ được chia sẻ vẫn có thể cần thiết bởi các quy trình khác, phương thức

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
6 nên được gọi. Khi một khối bộ nhớ chia sẻ không còn cần thiết bởi bất kỳ quy trình nào, phương thức
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
7 nên được gọi để đảm bảo dọn dẹp thích hợp.

Tên là tên duy nhất cho bộ nhớ chia sẻ được yêu cầu, được chỉ định là một chuỗi. Khi tạo một khối bộ nhớ chia sẻ mới, nếu

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
8 (mặc định) được cung cấp cho tên, một tên mới sẽ được tạo.

Tạo các điều khiển xem một khối bộ nhớ chia sẻ mới được tạo (

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
9) hoặc khối bộ nhớ chia sẻ hiện có được đính kèm (
>>> from multiprocessing import shared_memory
>>> shm_a = shared_memory.SharedMemory(create=True, size=10)
>>> type(shm_a.buf)
<class 'memoryview'>
>>> buffer = shm_a.buf
>>> len(buffer)
10
>>> buffer[:4] = bytearray([22, 33, 44, 55])  # Modify multiple at once
>>> buffer[4] = 100                           # Modify single byte at a time
>>> # Attach to an existing shared memory block
>>> shm_b = shared_memory.SharedMemory(shm_a.name)
>>> import array
>>> array.array('b', shm_b.buf[:5])  # Copy the data into a new array.array
array('b', [22, 33, 44, 55, 100])
>>> shm_b.buf[:5] = b'howdy'  # Modify via shm_b using bytes
>>> bytes(shm_a.buf[:5])      # Access via shm_a
b'howdy'
>>> shm_b.close()   # Close each SharedMemory instance
>>> shm_a.close()
>>> shm_a.unlink()  # Call unlink only once to release the shared memory
0).

Kích thước chỉ định số byte được yêu cầu khi tạo khối bộ nhớ chia sẻ mới. Bởi vì một số nền tảng chọn phân bổ các khối bộ nhớ dựa trên kích thước trang bộ nhớ của nền tảng đó, kích thước chính xác của khối bộ nhớ chia sẻ có thể lớn hơn hoặc bằng kích thước được yêu cầu. Khi gắn vào khối bộ nhớ chia sẻ hiện có, tham số

>>> from multiprocessing import shared_memory
>>> shm_a = shared_memory.SharedMemory(create=True, size=10)
>>> type(shm_a.buf)
<class 'memoryview'>
>>> buffer = shm_a.buf
>>> len(buffer)
10
>>> buffer[:4] = bytearray([22, 33, 44, 55])  # Modify multiple at once
>>> buffer[4] = 100                           # Modify single byte at a time
>>> # Attach to an existing shared memory block
>>> shm_b = shared_memory.SharedMemory(shm_a.name)
>>> import array
>>> array.array('b', shm_b.buf[:5])  # Copy the data into a new array.array
array('b', [22, 33, 44, 55, 100])
>>> shm_b.buf[:5] = b'howdy'  # Modify via shm_b using bytes
>>> bytes(shm_a.buf[:5])      # Access via shm_a
b'howdy'
>>> shm_b.close()   # Close each SharedMemory instance
>>> shm_a.close()
>>> shm_a.unlink()  # Call unlink only once to release the shared memory
1 bị bỏ qua.

gần()¶()

Đóng quyền truy cập vào bộ nhớ chia sẻ từ trường hợp này. Để đảm bảo dọn dẹp các tài nguyên thích hợp, tất cả các trường hợp nên gọi

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
6 sau khi trường hợp không còn cần thiết. Lưu ý rằng việc gọi
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
6 không làm cho khối bộ nhớ được chia sẻ bị phá hủy.

không liên kết () ¶()

Yêu cầu khối bộ nhớ chia sẻ cơ bản bị phá hủy. Để đảm bảo dọn dẹp các tài nguyên thích hợp,

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
7 nên được gọi một lần (và chỉ một lần) trên tất cả các quy trình cần khối bộ nhớ chia sẻ. Sau khi yêu cầu sự phá hủy của nó, một khối bộ nhớ chung có thể bị phá hủy ngay lập tức và hành vi này có thể khác nhau giữa các nền tảng. Các nỗ lực truy cập dữ liệu bên trong khối bộ nhớ được chia sẻ sau khi
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
7 được gọi là có thể dẫn đến lỗi truy cập bộ nhớ. Lưu ý: Quá trình cuối cùng từ bỏ việc giữ một khối bộ nhớ chung có thể gọi
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
7 và
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
6 theo một trong hai thứ tự.

buf¶

Một bộ nhớ của nội dung của khối bộ nhớ chia sẻ.

Tên¶

Truy cập chỉ đọc vào tên duy nhất của khối bộ nhớ chia sẻ.

kích thước¶

Truy cập chỉ đọc vào kích thước trong byte của khối bộ nhớ chia sẻ.

Ví dụ sau đây cho thấy việc sử dụng mức độ thấp của các trường hợp

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2:

>>> from multiprocessing import shared_memory
>>> shm_a = shared_memory.SharedMemory(create=True, size=10)
>>> type(shm_a.buf)
<class 'memoryview'>
>>> buffer = shm_a.buf
>>> len(buffer)
10
>>> buffer[:4] = bytearray([22, 33, 44, 55])  # Modify multiple at once
>>> buffer[4] = 100                           # Modify single byte at a time
>>> # Attach to an existing shared memory block
>>> shm_b = shared_memory.SharedMemory(shm_a.name)
>>> import array
>>> array.array('b', shm_b.buf[:5])  # Copy the data into a new array.array
array('b', [22, 33, 44, 55, 100])
>>> shm_b.buf[:5] = b'howdy'  # Modify via shm_b using bytes
>>> bytes(shm_a.buf[:5])      # Access via shm_a
b'howdy'
>>> shm_b.close()   # Close each SharedMemory instance
>>> shm_a.close()
>>> shm_a.unlink()  # Call unlink only once to release the shared memory

Ví dụ sau đây cho thấy việc sử dụng thực tế của lớp

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2 với các mảng numpy, truy cập cùng một
>>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:]  # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name  # We did not specify a name so one was chosen for us
'psm_21467_46075'

>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([  1,   1,   2,   3,   5, 888])

>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([  1,   1,   2,   3,   5, 888])

>>> # Clean up from within the second Python shell
>>> del c  # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()

>>> # Clean up from within the first Python shell
>>> del b  # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink()  # Free and release the shared memory block at the very end
0 từ hai vỏ Python riêng biệt:

>>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:]  # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name  # We did not specify a name so one was chosen for us
'psm_21467_46075'

>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([  1,   1,   2,   3,   5, 888])

>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([  1,   1,   2,   3,   5, 888])

>>> # Clean up from within the second Python shell
>>> del c  # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()

>>> # Clean up from within the first Python shell
>>> del b  # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink()  # Free and release the shared memory block at the very end

ClassMultipRocessing.Managers.SharedMemoryManager ([Địa chỉ [, AuthKey]]) ¶multiprocessing.managers.SharedMemoryManager([address[, authkey]])

Một lớp con của

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
3 có thể được sử dụng để quản lý các khối bộ nhớ được chia sẻ trong các quy trình.

Một cuộc gọi đến

>>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:]  # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name  # We did not specify a name so one was chosen for us
'psm_21467_46075'

>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([  1,   1,   2,   3,   5, 888])

>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([  1,   1,   2,   3,   5, 888])

>>> # Clean up from within the second Python shell
>>> del c  # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()

>>> # Clean up from within the first Python shell
>>> del b  # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink()  # Free and release the shared memory block at the very end
2 trên một ví dụ
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
4 khiến một quy trình mới được bắt đầu. Mục đích duy nhất của quy trình mới này là quản lý vòng đời của tất cả các khối bộ nhớ được chia sẻ được tạo ra thông qua nó. Để kích hoạt việc phát hành tất cả các khối bộ nhớ được chia sẻ được quản lý bởi quy trình đó, hãy gọi
>>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:]  # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name  # We did not specify a name so one was chosen for us
'psm_21467_46075'

>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([  1,   1,   2,   3,   5, 888])

>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([  1,   1,   2,   3,   5, 888])

>>> # Clean up from within the second Python shell
>>> del c  # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()

>>> # Clean up from within the first Python shell
>>> del b  # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink()  # Free and release the shared memory block at the very end
4 trên ví dụ. Điều này kích hoạt một cuộc gọi
>>> # In the first Python interactive shell
>>> import numpy as np
>>> a = np.array([1, 1, 2, 3, 5, 8])  # Start with an existing NumPy array
>>> from multiprocessing import shared_memory
>>> shm = shared_memory.SharedMemory(create=True, size=a.nbytes)
>>> # Now create a NumPy array backed by shared memory
>>> b = np.ndarray(a.shape, dtype=a.dtype, buffer=shm.buf)
>>> b[:] = a[:]  # Copy the original data into shared memory
>>> b
array([1, 1, 2, 3, 5, 8])
>>> type(b)
<class 'numpy.ndarray'>
>>> type(a)
<class 'numpy.ndarray'>
>>> shm.name  # We did not specify a name so one was chosen for us
'psm_21467_46075'

>>> # In either the same shell or a new Python shell on the same machine
>>> import numpy as np
>>> from multiprocessing import shared_memory
>>> # Attach to the existing shared memory block
>>> existing_shm = shared_memory.SharedMemory(name='psm_21467_46075')
>>> # Note that a.shape is (6,) and a.dtype is np.int64 in this example
>>> c = np.ndarray((6,), dtype=np.int64, buffer=existing_shm.buf)
>>> c
array([1, 1, 2, 3, 5, 8])
>>> c[-1] = 888
>>> c
array([  1,   1,   2,   3,   5, 888])

>>> # Back in the first Python interactive shell, b reflects this change
>>> b
array([  1,   1,   2,   3,   5, 888])

>>> # Clean up from within the second Python shell
>>> del c  # Unnecessary; merely emphasizing the array is no longer used
>>> existing_shm.close()

>>> # Clean up from within the first Python shell
>>> del b  # Unnecessary; merely emphasizing the array is no longer used
>>> shm.close()
>>> shm.unlink()  # Free and release the shared memory block at the very end
5 trên tất cả các đối tượng
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2 được quản lý bởi quá trình đó và sau đó dừng quá trình này. Bằng cách tạo các phiên bản
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2 thông qua
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
4, chúng tôi tránh được sự cần thiết phải theo dõi thủ công và kích hoạt việc giải phóng các tài nguyên bộ nhớ được chia sẻ.

Lớp này cung cấp các phương thức để tạo và trả về các phiên bản

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2 và để tạo một đối tượng giống như danh sách (
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0) được hỗ trợ bởi bộ nhớ chia sẻ.

Tham khảo

>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
1 để biết mô tả về địa chỉ được kế thừa và các đối số đầu vào tùy chọn AuthKey và cách chúng có thể được sử dụng để kết nối với dịch vụ
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
4 hiện có từ các quy trình khác.

SharedMemory (Kích thước) ¶(size)

Tạo và trả về một đối tượng

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2 mới với
>>> from multiprocessing import shared_memory
>>> shm_a = shared_memory.SharedMemory(create=True, size=10)
>>> type(shm_a.buf)
<class 'memoryview'>
>>> buffer = shm_a.buf
>>> len(buffer)
10
>>> buffer[:4] = bytearray([22, 33, 44, 55])  # Modify multiple at once
>>> buffer[4] = 100                           # Modify single byte at a time
>>> # Attach to an existing shared memory block
>>> shm_b = shared_memory.SharedMemory(shm_a.name)
>>> import array
>>> array.array('b', shm_b.buf[:5])  # Copy the data into a new array.array
array('b', [22, 33, 44, 55, 100])
>>> shm_b.buf[:5] = b'howdy'  # Modify via shm_b using bytes
>>> bytes(shm_a.buf[:5])      # Access via shm_a
b'howdy'
>>> shm_b.close()   # Close each SharedMemory instance
>>> shm_a.close()
>>> shm_a.unlink()  # Call unlink only once to release the shared memory
1 được chỉ định trong byte.

ShareAblelist (trình tự) ¶(sequence)

Tạo và trả về một đối tượng

>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0 mới, được khởi tạo bởi các giá trị từ đầu vào
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
6.

Ví dụ sau đây cho thấy các cơ chế cơ bản của

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
4:

>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl

Ví dụ sau đây mô tả một mẫu có khả năng thuận tiện hơn để sử dụng các đối tượng

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
4 thông qua câu lệnh
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
9 để đảm bảo rằng tất cả các khối bộ nhớ được chia sẻ được phát hành sau khi chúng không còn cần thiết:

>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl

Khi sử dụng

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
4 trong câu lệnh
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
9, các khối bộ nhớ được chia sẻ được tạo bằng cách sử dụng trình quản lý đó đều được phát hành khi khối mã
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
9 Khối mã mã hoàn thành thực thi.

ClassMultipRocessing.Shared_Memory.ShareAblelist (sequence = none, *, name = none) ¶multiprocessing.shared_memory.ShareableList(sequence=None, *, name=None)

Cung cấp một đối tượng giống như danh sách có thể thay đổi trong đó tất cả các giá trị được lưu trữ bên trong được lưu trữ trong một khối bộ nhớ được chia sẻ. Điều này ràng buộc các giá trị có thể lưu trữ chỉ với

>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl
3,
>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl
4,
>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl
5,
>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl
6 (mỗi byte dưới 10m),
>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl
7 (mỗi byte dưới 10m) và các loại dữ liệu tích hợp
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
8. Nó cũng khác biệt đáng kể so với loại
>>> with SharedMemoryManager() as smm:
...     sl = smm.ShareableList(range(2000))
...     # Divide the work among two processes, storing partial results in sl
...     p1 = Process(target=do_work, args=(sl, 0, 1000))
...     p2 = Process(target=do_work, args=(sl, 1000, 2000))
...     p1.start()
...     p2.start()  # A multiprocessing.Pool might be more efficient
...     p1.join()
...     p2.join()   # Wait for all work to complete in both processes
...     total_result = sum(sl)  # Consolidate the partial results now in sl
9 tích hợp ở chỗ các danh sách này không thể thay đổi độ dài tổng thể của chúng (nghĩa là không có thêm, chèn, v.v.) và không hỗ trợ tạo ra các trường hợp
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0 mới thông qua cắt.

Trình tự được sử dụng trong việc điền vào một

>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0 mới đầy đủ các giá trị. Thay vào đó, được đặt thành
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
8 để gắn vào
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0 đã tồn tại bằng tên bộ nhớ được chia sẻ duy nhất của nó.

Tên là tên duy nhất cho bộ nhớ chia sẻ được yêu cầu, như được mô tả trong định nghĩa cho

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2. Khi gắn vào
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0 hiện có, chỉ định tên duy nhất của khối bộ nhớ được chia sẻ trong khi để
>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
6 được đặt thành
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
8.

Đếm (giá trị) ¶(value)

Trả về số lần xuất hiện của

>>> from multiprocessing import shared_memory
>>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
>>> [ type(entry) for entry in a ]
[<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
>>> a[2]
-273.154
>>> a[2] = -78.5
>>> a[2]
-78.5
>>> a[2] = 'dry ice'  # Changing data types is supported as well
>>> a[2]
'dry ice'
>>> a[2] = 'larger than previously allocated storage space'
Traceback (most recent call last):
  ...
ValueError: exceeds available storage for existing str
>>> a[2]
'dry ice'
>>> len(a)
7
>>> a.index(42)
6
>>> a.count(b'howdy')
0
>>> a.count(b'HoWdY')
1
>>> a.shm.close()
>>> a.shm.unlink()
>>> del a  # Use of a ShareableList after call to unlink() is unsupported
8.

chỉ mục (giá trị) ¶(value)

Trả về vị trí chỉ mục đầu tiên của

>>> from multiprocessing import shared_memory
>>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
>>> [ type(entry) for entry in a ]
[<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
>>> a[2]
-273.154
>>> a[2] = -78.5
>>> a[2]
-78.5
>>> a[2] = 'dry ice'  # Changing data types is supported as well
>>> a[2]
'dry ice'
>>> a[2] = 'larger than previously allocated storage space'
Traceback (most recent call last):
  ...
ValueError: exceeds available storage for existing str
>>> a[2]
'dry ice'
>>> len(a)
7
>>> a.index(42)
6
>>> a.count(b'howdy')
0
>>> a.count(b'HoWdY')
1
>>> a.shm.close()
>>> a.shm.unlink()
>>> del a  # Use of a ShareableList after call to unlink() is unsupported
8. Tăng
>>> b = shared_memory.ShareableList(range(5))         # In a first process
>>> c = shared_memory.ShareableList(name=b.shm.name)  # In a second process
>>> c
ShareableList([0, 1, 2, 3, 4], name='...')
>>> c[-1] = -999
>>> b[-1]
-999
>>> b.shm.close()
>>> c.shm.close()
>>> c.shm.unlink()
0 nếu
>>> from multiprocessing import shared_memory
>>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
>>> [ type(entry) for entry in a ]
[<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
>>> a[2]
-273.154
>>> a[2] = -78.5
>>> a[2]
-78.5
>>> a[2] = 'dry ice'  # Changing data types is supported as well
>>> a[2]
'dry ice'
>>> a[2] = 'larger than previously allocated storage space'
Traceback (most recent call last):
  ...
ValueError: exceeds available storage for existing str
>>> a[2]
'dry ice'
>>> len(a)
7
>>> a.index(42)
6
>>> a.count(b'howdy')
0
>>> a.count(b'HoWdY')
1
>>> a.shm.close()
>>> a.shm.unlink()
>>> del a  # Use of a ShareableList after call to unlink() is unsupported
8 không có mặt.

định dạng¶

Thuộc tính chỉ đọc có chứa định dạng đóng gói

>>> b = shared_memory.ShareableList(range(5))         # In a first process
>>> c = shared_memory.ShareableList(name=b.shm.name)  # In a second process
>>> c
ShareableList([0, 1, 2, 3, 4], name='...')
>>> c[-1] = -999
>>> b[-1]
-999
>>> b.shm.close()
>>> c.shm.close()
>>> c.shm.unlink()
2 được sử dụng bởi tất cả các giá trị hiện đang được lưu trữ.

shm¶

Ví dụ

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2 nơi các giá trị được lưu trữ.

Ví dụ sau đây cho thấy việc sử dụng cơ bản một thể hiện

>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0:

>>> from multiprocessing import shared_memory
>>> a = shared_memory.ShareableList(['howdy', b'HoWdY', -273.154, 100, None, True, 42])
>>> [ type(entry) for entry in a ]
[<class 'str'>, <class 'bytes'>, <class 'float'>, <class 'int'>, <class 'NoneType'>, <class 'bool'>, <class 'int'>]
>>> a[2]
-273.154
>>> a[2] = -78.5
>>> a[2]
-78.5
>>> a[2] = 'dry ice'  # Changing data types is supported as well
>>> a[2]
'dry ice'
>>> a[2] = 'larger than previously allocated storage space'
Traceback (most recent call last):
  ...
ValueError: exceeds available storage for existing str
>>> a[2]
'dry ice'
>>> len(a)
7
>>> a.index(42)
6
>>> a.count(b'howdy')
0
>>> a.count(b'HoWdY')
1
>>> a.shm.close()
>>> a.shm.unlink()
>>> del a  # Use of a ShareableList after call to unlink() is unsupported

Ví dụ sau đây mô tả cách một, hai hoặc nhiều quy trình có thể truy cập cùng

>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0 bằng cách cung cấp tên của khối bộ nhớ chia sẻ đằng sau nó:

>>> b = shared_memory.ShareableList(range(5))         # In a first process
>>> c = shared_memory.ShareableList(name=b.shm.name)  # In a second process
>>> c
ShareableList([0, 1, 2, 3, 4], name='...')
>>> c[-1] = -999
>>> b[-1]
-999
>>> b.shm.close()
>>> c.shm.close()
>>> c.shm.unlink()

Các ví dụ sau đây chứng minh rằng các đối tượng

>>> from multiprocessing.managers import SharedMemoryManager
>>> smm = SharedMemoryManager()
>>> smm.start()  # Start the process that manages the shared memory blocks
>>> sl = smm.ShareableList(range(4))
>>> sl
ShareableList([0, 1, 2, 3], name='psm_6572_7512')
>>> raw_shm = smm.SharedMemory(size=128)
>>> another_sl = smm.ShareableList('alpha')
>>> another_sl
ShareableList(['a', 'l', 'p', 'h', 'a'], name='psm_6572_12221')
>>> smm.shutdown()  # Calls unlink() on sl, raw_shm, and another_sl
0 (và bên dưới
from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
2) có thể được ngâm và không bị ràng buộc nếu cần. Lưu ý rằng nó vẫn sẽ là cùng một đối tượng được chia sẻ. Điều này xảy ra, bởi vì đối tượng khử Deserialized có cùng tên duy nhất và chỉ được gắn vào một đối tượng hiện có có cùng tên (nếu đối tượng vẫn còn sống):

>>> import pickle
>>> from multiprocessing import shared_memory
>>> sl = shared_memory.ShareableList(range(10))
>>> list(sl)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

>>> deserialized_sl = pickle.loads(pickle.dumps(sl))
>>> list(deserialized_sl)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
0

from multiprocessing import Process, Queue, Value, Manager
from ctypes import c_bool
from threading import Thread


ps = []

def yourFunc(pause, budget):
    while True:
        print(budget.value, pause.value)
        ##set value
        pause.value = True  
        ....

def multiProcess(threads, pause, budget):
    for _ in range(threads):
        t = Thread(target=yourFunc(), args=(pause, budget,)) 
        t.start()
        ts.append(t)
        time.sleep(3)

if __name__ == '__main__':
    pause = Value(c_bool, False)
    budget = Value('i', 5000)

    for i in range(2):
        p = Process(target=multiProcess, args=(2, pause, budget))
        p.start()
        ps.append(p) 
1

Làm cách nào để chia sẻ dữ liệu giữa hai quy trình trong Python?

Chuyển tin nhắn để xử lý một cách đơn giản để giao tiếp giữa quy trình với đa xử lý là sử dụng hàng đợi để truyền tin nhắn qua lại. Bất kỳ đối tượng có thể dưa chua có thể đi qua hàng đợi. Ví dụ ngắn này chỉ chuyển một tin nhắn cho một công nhân duy nhất, sau đó quá trình chính chờ người lao động hoàn thành.use a Queue to pass messages back and forth. Any pickle-able object can pass through a Queue. This short example only passes a single message to a single worker, then the main process waits for the worker to finish.

Làm thế nào để bạn truyền đạt hai quá trình trong Python?

Mỗi đối tượng có hai phương thức - gửi () và recv (), để giao tiếp giữa các quy trình.send() and recv(), to communicate between processes.

Các quy trình python có chia sẻ bộ nhớ không?

Bộ nhớ chia sẻ có thể là một cách xử lý dữ liệu rất hiệu quả trong một chương trình sử dụng đồng thời.MMAP của Python sử dụng bộ nhớ được chia sẻ để chia sẻ một cách hiệu quả số lượng lớn dữ liệu giữa nhiều quy trình, luồng và các tác vụ đang xảy ra đồng thời.Python's mmap uses shared memory to efficiently share large amounts of data between multiple Python processes, threads, and tasks that are happening concurrently.

Làm thế nào để đa xử lý hoạt động trong Python?

Đa xử lý là một gói hỗ trợ các quy trình sinh sản bằng API tương tự như mô -đun luồng.Gói đa xử lý cung cấp cả đồng thời cục bộ và từ xa, bước hiệu quả là khóa thông dịch toàn cầu bằng cách sử dụng các quy trình phụ thay vì các luồng.supports spawning processes using an API similar to the threading module. The multiprocessing package offers both local and remote concurrency, effectively side-stepping the Global Interpreter Lock by using subprocesses instead of threads.