共享内存小记


Shared Memory

    Shared Memory is easily to understand, especially after grasping semaphore.

    Normally, if we execute a piece of program twice (make them running at the same time), variables with the same name will occupy different physical memory. That means if in p1(one of the running process) the system makes x++, in p2(another running process) the same-name variable x will not be affected.

    But sometimes we need that the 2 processes could influence each other for communication, then we can use shared memory.

    Similar to semaphore, we use get function to obtain an ID.

        int shmget(key_t key, size_t size, int shmflg);

    shmget() returns an ID pointing to the shared memory associated to the parameter key. The 2nd argument size indicates the memory size that will be allocated, And we usually set shmflg to 0666 | IPC_CREAT.

    After we execute the shmget() function, the memory could not be accessed yet. We should use shmat() to attach the shared memory to the calling process, so that the process could perform operations on the memory.

       void *shmat(int shmid, const void *shmaddr, int shmflg);

    shmid is the ID returned by shmget(). If we set shmaddr to (void *)0, the system will find a suitable memory to allocate. And usually we set shmflg to 0.

    The opposite one to shmat() is shmdt() -- to detach the shared memory from the calling process so that the process could not operate with it any more unless shmat() again.

    The prototype of shmdt() is :

       int shmdt(const void *shmaddr);

    Finally, we use shmctl() to remove the shared memory.

    Usually we use shmctl(shmid, IPC_RMID, 0).

 

    以下是一个小实验,我们用shm1.c来对共享内存写消息,然后用shm2.c来读取。

shm1.c:

shm2.c:

    对两段代码编譯执行:

       需要注意的是对共享内存的读写并不是原子操作,可能出现读到一半的时候另一个进程重写了共享内存,这样难免会出现错误。 关于这一点,则需要编程人员来控制。


Jason Lee

2009-11-15 p.m

Protobuf是一种高效的序列化协议,可以用于数据交换和数据存储。它的主要优势是大小小,速度快,可扩展性强。下面是使用Protobuf的一些小记: 1. 定义消息格式 首先,需要定义消息格式,以便Protobuf可以将数据序列化和反序列化。消息格式定义在.proto文件中,使用protobuf语言编。例如,下面是一个简单的消息格式定义: ``` syntax = "proto3"; message Person { string name = 1; int32 age = 2; } ``` 这个消息格式定义了一个名为Person的消息,包含两个字段:name和age。 2. 生成代码 一旦消息格式定义好,就可以使用Protobuf编译器生成代码。编译器将根据消息格式定义生成相应的代码,包括消息类、序列化和反序列化方法等。可以使用以下命令生成代码: ``` protoc --java_out=. message.proto ``` 这将生成一个名为message.pb.java的Java类,该类包含Person消息的定义以及相关方法。 3. 序列化和反序列化 一旦生成了代码,就可以使用Protobuf序列化和反序列化数据。例如,下面是一个示例代码,将一个Person对象序列化为字节数组,并将其反序列化为另一个Person对象: ``` Person person = Person.newBuilder() .setName("Alice") .setAge(25) .build(); byte[] bytes = person.toByteArray(); Person deserializedPerson = Person.parseFrom(bytes); ``` 这个示例代码创建了一个Person对象,将其序列化为字节数组,然后将其反序列化为另一个Person对象。在这个过程中,Protobuf使用生成的代码执行序列化和反序列化操作。 以上是使用Protobuf的一些基本步骤和注意事项,希望对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值