My program has 2 threads, I use shared memory to communicate between the two.
Each thread has an ‘init’ method. In the init method, I call ‘shmget’ and ‘shmat’ to get the shared memory segment and attach to local variable. A portion of the code is like below:
Thread 1 (which runs first):
void init() {
this->segment_id = shmget(SAME_KEY,SAME_SIZE,IPC_CREAT|S_IRUSR|S_IWUSR|S_IROTH|S_IWOTH);
this->data = shmat(this->segment_id,0,0);
}
Thread 2 (which runs after thread 1):
void init() {
this->segment_id = shmget(SAME_KEY,SAME_SIZE,0);
this->data = shmat(this->segment_id,0,0);
}
The program is running but it gives unexpected result. What I’m afraid is that the call to ‘shmat’ in the second thread may make the ‘data’ in thread 1 inaccessible or some sort of malfunctionality. The fact is that, in thread 1 I can access the whole shared segment, but in thread 2 I can access only the first 16 bytes, so I don’t know what’s happening.
Does this mean each shared memory segment can be attached to 1 location at a time?
Is it ok to call ‘shmat’ twice to make the shared memory accessible from different pointers?
Each shared memory segment can be attached to multiple locations at a time. It ok to call ‘shmat’ twice to make the shared memory accessible from different pointers.
I suspect that in the given example you can’t be sure that Thread1::init() is called before Thread2::init() so in Thread2 you are accessing not created memory – so that is the reason for observed problems.
Use IPC_CREAT for both calls (without IPC_EXCL of course).
See manpage