【发布时间】:2019-10-25 09:53:58
【问题描述】:
对于我的项目,我有两个任务 1)Writer : 将值写入共享内存的结构中 2)Reader:从结构中读取值
这是编写器代码
struct test {
volatile int read;
volatile int write;
};
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
struct test *t = (struct test *) shmat(shmid,(void*)0,0);
printf("Going to write into test structure");
t->read = 1;
t->write = 2;
//printf("Data written in memory: %s\n",str);
//detach from shared memory
shmdt((void *)t);
return 0;
}
这是阅读器代码
int main()
{
// ftok to generate unique key
key_t key = ftok("shmfile",65);
// shmget returns an identifier in shmid
int shmid = shmget(key,1024,0666|IPC_CREAT);
// shmat to attach to shared memory
struct test *t = (struct test *) shmat(shmid,(void*)0,0);
printf("Data read from memory: %d:%d\n",t->read,t->write);
//detach from shared memory
shmdt((void *)t);
// destroy the shared memory
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
当我先运行 writer 然后运行 reader 时,一切正常。
但为了调试,我尝试通过 lldb 同时运行两者。我看看作者是否写了 t->read = 1 ,同时它不会在阅读器进程中得到更新。如果在更改完成后调用 shmat,它将反映在阅读器中。
谁能告诉我,如何确保共享内存中的更改同步发生?
【问题讨论】:
-
这些演员表有什么用?
-
您能详细说明一下吗?哪个演员?
-
全部。而且您需要一个信号量或互斥锁来同步读取和写入。
-
... 其中,除了同步之外,信号量更适合确保编写者先行。
标签: c linux synchronization ipc shared-memory