Python處理序間通訊之共用記憶體

來源:互聯網
上載者:User

標籤:例子   部落格   tty   map   具體細節   地址   int   實現   進程地址空間   

前一篇部落格說了怎樣通過具名管道實現處理序間通訊,但是要在windows是使用具名管道,需要使用python調研windows api,太麻煩,於是想到是不是可以通過共用記憶體的方式來實現。查了一下,Python中可以使用mmap模組來實現這一功能。

Python中的mmap模組是通過映射同一個普通檔案實現共用記憶體的。檔案被映射到進程地址空間後,進程可以像訪問記憶體一樣對檔案進行訪問。

不過,mmap在linux和windows上的API有些許的不一樣,具體細節可以查看mmap的文檔。

下面看一個例子:

server.py

這個程式使用 test.dat 檔案來映射記憶體,並且分配了1024位元組的大小,每隔一秒更新一下記憶體資訊。

import mmapimport contextlibimport timewith 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 mmapimport contextlibimport timewhile 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 mmapimport contextlibimport timewith 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 mmapimport contextlibimport timewhile 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)

Python處理序間通訊之共用記憶體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.