这在 UNIX 系统上是微不足道的;只需使用共享内存功能:
shgmet、shmat、shmctl、shmdt
void *shmat(int shmid, const void *shmaddr, int shmflg);
shmat() 将由 shmid 标识的共享内存段附加到调用进程的地址空间。附加地址由 shmaddr 指定,具有以下条件之一:
如果 shmaddr 为 NULL,则系统选择一个合适的(未使用的)地址来附加该段。
只需在此处指定您自己的地址;例如0x20000000000
如果您在每个进程中使用相同的密钥和大小 shmget(),您将获得相同的共享内存段。如果您 shmat() 在同一地址,则所有进程中的虚拟地址将相同。内核不关心你使用什么地址范围,只要它不与它通常分配东西的地方冲突。(如果省略地址,您可以看到它喜欢放置东西的一般区域;此外,检查堆栈上的地址并从 malloc() / new[] 返回。)
在 Linux 上,确保 root 将 /proc/sys/kernel/shmmax 中的 SHMMAX 设置为足够大的数字以容纳您的共享内存段(默认为 32MB)。
至于原子操作,您可以从 Linux 内核源代码中获取它们,例如
包括/asm-x86/atomic_64.h
/*
* Make sure gcc doesn't try to be clever and move things around
* on us. We need to use _exactly_ the address the user gave us,
* not some alias that contains the same information.
*/
typedef struct {
int counter;
} atomic_t;
/**
* atomic_read - read atomic variable
* @v: pointer of type atomic_t
*
* Atomically reads the value of @v.
*/
#define atomic_read(v) ((v)->counter)
/**
* atomic_set - set atomic variable
* @v: pointer of type atomic_t
* @i: required value
*
* Atomically sets the value of @v to @i.
*/
#define atomic_set(v, i) (((v)->counter) = (i))
/**
* atomic_add - add integer to atomic variable
* @i: integer value to add
* @v: pointer of type atomic_t
*
* Atomically adds @i to @v.
*/
static inline void atomic_add(int i, atomic_t *v)
{
asm volatile(LOCK_PREFIX "addl %1,%0"
: "=m" (v->counter)
: "ir" (i), "m" (v->counter));
}
64 位版本:
typedef struct {
long counter;
} atomic64_t;
/**
* atomic64_add - add integer to atomic64 variable
* @i: integer value to add
* @v: pointer to type atomic64_t
*
* Atomically adds @i to @v.
*/
static inline void atomic64_add(long i, atomic64_t *v)
{
asm volatile(LOCK_PREFIX "addq %1,%0"
: "=m" (v->counter)
: "er" (i), "m" (v->counter));
}