前一篇博客說了怎樣通過命名管道實現進程間通信,但是要在windows是使用命名管道,需要使用python調研windows api,太麻煩,於是想到是不是可以通過共享內存的方式來實現。查了一下,Python中可以使用mmap模塊來實現這一功能。
Python中的mmap模塊是通過映射同一個普通文件實現共享內存的。文件被映射到進程地址空間后,進程可以像訪問內存一樣對文件進行訪問。
不過,mmap在linux和windows上的API有些許的不一樣,具體細節可以查看mmap的文檔。
下面看一個例子:
server.py
這個程序使用 test.dat 文件來映射內存,並且分配了1024字節的大小,每隔一秒更新一下內存信息。
import mmap import contextlib import time with open("test.dat", "w") as f: f.write('\x00' * 1024) with open('test.dat', 'r+') as f: with contextlib.closing(mmap.mmap(f.fileno(), 1024, access=mmap.ACCESS_WRITE)) as m: for i in range(1, 10001): m.seek(0) s = "msg " + str(i) s.rjust(1024, '\x00') m.write(s) m.flush() time.sleep(1)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
client.py
這個程序從上面映射的文件 test.dat 中加載數據到內存中。
import mmap import contextlib import time while True: with open('test.dat', 'r') as f: with contextlib.closing(mmap.mmap(f.fileno(), 1024, access=mmap.ACCESS_READ)) as m: s = m.read(1024).replace('\x00', '') print s time.sleep(1)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
上面的代碼可以在linux和windows上運行,因為我們明確指定了使用 test.dat 文件來映射內存。如果我們只需要在windows上實現共享內存,可以不用指定使用的文件,而是通過指定一個tagname來標識,所以可以簡化上面的代碼。如下:
server.py
import mmap import contextlib import time with contextlib.closing(mmap.mmap(-1, 1024, tagname='test', access=mmap.ACCESS_WRITE)) as m: for i in range(1, 10001): m.seek(0) m.write("msg " + str(i)) m.flush() time.sleep(1)
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
client.py
import mmap import contextlib import time while True: with contextlib.closing(mmap.mmap(-1, 1024, tagname='test', access=mmap.ACCESS_READ)) as m: s = m.read(1024).replace('\x00', '') print s time.sleep(1)