Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
938 views
in Technique[技术] by (71.8m points)

c++ - c++11 interprocess atomics and mutexes

I have a Linux program which spawns several processes (fork) and communicates through POSIX Shared Memory. I'd like to have each process allocate an id (0-255). My intention is to place a bitvector in the shared memory region (initialized to zero) and atomically compare and swap a bit to allocate an id.

Is there a c++11-friendly way to do this? Can I create an atomic bitset? Can I use a mutex across processes? How do I assure that constructors get called once and only once across all processes?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The C++11 threading primitives (mutexes, atomics, etc) are threading primitives. The C++ standard doesn't reference processes, and most of these tools don't interoperate across processes.

The only mention of processes in the standard is in a non-normative notation that says that lock-free atomics are intended to be OK for IPC:

Operations that are lock-free should also be address-free. That is, atomic operations on the same memory location via two different addresses will communicate atomically. The implementation should not depend on any per-process state. This restriction enables communication by memory that is mapped into a process more than once and by memory that is shared between two processes.

Outside of this non-normative notation, the threading primitives are not intended to be a means of achieving inter-process communication. The behavior of such objects when placed in shared memory (aside from lock-free atomics as noted above) is undefined.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...