最近我一直在玩IPC使用共享内存.我一直试图实现的一件事是一个简单的环形缓冲区,其中包含1个进程生成和1个进程消耗.每个进程都有自己的序列号来跟踪其位置.使用原子操作更新这些序列号,以确保其他进程可以看到正确的值.一旦环形缓冲区已满,生产者将阻止.代码是无锁的,因为没有使用信号量或互斥量.
性能方面我在相当适中的VM上每秒获得大约2000万条消息 - 非常满意:)
我对我的代码是如何"正确"感到好奇.有人能发现任何固有问题/竞争条件吗?这是我的代码.提前感谢您的任何意见.
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>
#include <string.h>
#define SHM_ID "/mmap-test"
#define BUFFER_SIZE 4096
#define SLEEP_NANOS 1000 // 1 micro
struct Message
{
long _id;
char _data[128];
};
struct RingBuffer
{
size_t _rseq;
char _pad1[64];
size_t _wseq;
char _pad2[64];
Message _buffer[BUFFER_SIZE];
};
void
producerLoop()
{
int size = sizeof( RingBuffer );
int fd = shm_open( SHM_ID, O_RDWR | O_CREAT, 0600 );
ftruncate( fd, size+1 );
// create …Run Code Online (Sandbox Code Playgroud)