python 、mmap 實現內存數據共享


import mmap
mmap_file = None


##從內存中讀取信息,
def read_mmap_info():    
    global mmap_file
    mmap_file.seek(0)
    ##把二進制轉換為字符串
    info_str=mmap_file.read().translate(None, b'\x00').decode()
    print(info_str)
##如果內存中沒有對應信息,則向內存中寫信息以供下次調用使用
def get_mmap_info():
    global mmap_file
    ##第二個參數1024是設定的內存大小,單位:字節。如果內容較多,可以調大一點
    mmap_file = mmap.mmap(-1, 1024, access = mmap.ACCESS_WRITE, tagname = 'share_mmap')
    ##讀取有效比特數,不包括空比特
    cnt=mmap_file.read_byte()
    if cnt==0:
        print("Load data to memory")
        mmap_file = mmap.mmap(0, 1024, access = mmap.ACCESS_WRITE, tagname = 'share_mmap')
        mmap_file.write(b"This is the test data")
    else :
        print("The data is in memory")
        read_mmap_info()

##修改內存塊中的數據
def reset_mmp_info:
    global mmap_file
    mmap_file.seek(0)
    mmap_file.write(b'\x00')
    mmap_file.write(b"Load data to memory agine")


if __name__=="__main__":
    get_mmap_info()


說明:如果是使用python自帶的IDE,請重新打開一次此文件運行測試數據裝載到內存后的結果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM