gpt4 book ai didi

C++ std lib , 库和共享内存

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:53:20 31 4
gpt4 key购买 nike

如果您想在共享内存中的进程之间共享互斥体,POSIX 线程的 C API 需要设置一个特殊标志 - 请参阅 sem_init()。我真的不知道差异是什么,但我在尝试在共享内存中使用 C++ std::condition_variable 时遇到了问题——它的段错误。我在 C++ 文档或构造函数中看不到任何提及此内容的内容。我想知道如何/是否可以在共享内存中使用 C++ 线程互斥锁。这是我的测试代码供引用。注意 squeue 只是一个简单的 (POD) 静态大小的循环队列,省略了不相关的内容:

#include <iostream>
#include <sys/mman.h>
#include <sys/stat.h> /* For mode constants */
#include <fcntl.h> /* For O_* constants */
#include "squeue.h"
#define SHM_FILENAME "/shimmy-foo"
#define SQUEUE_LENGTH 10

typedef struct {
squeue<int,SQUEUE_LENGTH> queue;
std::mutex mutex;
std::condition_variable_any condvar;
} SHM;

int main() {
int shm_fd = 0;
SHM * shm_ptr = NULL;
squeue<int,SQUEUE_LENGTH> * queue = NULL;
std::mutex * mutex;
std::condition_variable_any * condvar;

// Init SHM. ftruncate() will zero area.
if((shm_fd = shm_open(SHM_FILENAME, O_CREAT|O_RDWR|O_EXCL, S_IREAD|S_IWRITE)) == -1 ) {
fprintf (stderr, "Could not open shm object. %s\n", strerror(errno));
return errno;
}
else {
fprintf (stderr, "Open shm OK. %d\n", shm_fd);
}
ftruncate(shm_fd, sizeof(SHM));

// Connect the shmptr pointer to set to the shared memory area,
// with desired permissions
if((shm_ptr = (SHM*)mmap(0, sizeof(SHM), PROT_READ|PROT_WRITE, MAP_SHARED, shm_fd, 0)) == MAP_FAILED) {
fprintf (stderr, "Could not map shm. %s\n", strerror(errno));
return errno;
}
else {
fprintf(stderr, "Mapped shm OK. %p\n", shm_ptr);
}

// Create queue and mutex.
queue = new(&shm_ptr->queue) squeue<int,SQUEUE_LENGTH>();
mutex = new(&shm_ptr->mutex) std::mutex();
condvar = new(&shm_ptr->condvar) std::condition_variable_any();

srand(time(NULL));
while(true) {
cout << "Waiting on lock" << endl;
mutex->lock();
if(!queue->full()) {
int value = rand()%100;
queue->push(value);
cout << "Pushed " << value << endl;
} else {
cout << "Que is full!" << endl;
};
condvar->notify_all(); //Seg fault.
mutex->unlock();
sleep(1);
}
}

最佳答案

我使用了类似的模式,但是,标准互斥锁和条件变量并非设计为在进程之间共享。原因是 POSIX 需要在进程共享互斥锁和条件变量上设置 PTHREAD_PROCESS_SHARED 属性,但标准 C++ 原语不这样做。在 Windows 上,它可能比这更复杂。

您可以尝试使用 boost process shared mutexesprocess shared condition variables反而。或者为 POSIX 接口(interface)创建您自己的包装器。


也可能是 squeue 破坏了缓冲区以外的内存,覆盖了 struct SHM 内存中的互斥锁和条件变量。我会尝试注释掉推送到队列中的代码,看看您是否仍然遇到崩溃。我在注释掉队列代码的情况下尝试了您的代码,它按预期工作。


您可能还喜欢使用 condition_variable 而不是 condition_variable_any,因为后者维护自己的互斥锁,但如果您在通知条件变量的同时通知该条件变量,则不需要该互斥锁关联的互斥量已锁定(就像您所做的那样)。

关于C++ std lib <mutex>, <conditional_variable> 库和共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24360477/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com