我正在使用boost::interprocess::managed_shared_memory
进行进程间通信。为了增长/缩小,必须在使用它的每个进程中取消映射共享内存。鉴于我有两个线程,这是怎么做到的?
就我搜索boost
文档而言,没有像这样的unmap / detach函数,所以也许我只需要删除指针?这会工作:(未经测试/未编译)
MyThreadClass::operator() () {
// mutex for thread safe write of Abord/Done fields
std::pair<boost::interprocess::named_mutex*, std::size_t> mutex =
sharedSegment->find<boost::interprocess::named_mutex>("Mutex");
// stop all threads?
std::pair<bool*, std::size_t> abord = sharedSegment->find<bool>("Abord");
// is work of the thread done?
std::pair<bool*, std::size_t> done = sharedSegment->find<bool>("Done");
while(! (*abord.first) ) {
// id == id of thread, if more threads are used
if (! (done.first)[id] ) {
this->doSomethingUseful();
mutex.first->lock();
(done.first)[id] = true;
mutex.first->unlock();
} else {
// when work is done, this thread has nothing to do
// until the main application tells us so
// by the time we sleep, we can detach the shared memory
// do some busy waiting (change to observer pattern if everything works)
delete mutex;
delete abord;
delete done;
boost::this_thread::sleep(boost::posix_time::seconds(1));
// map variables again
mutex = sharedSegment->find<boost::interprocess::named_mutex>("Mutex");
abord = sharedSegment->find<bool>("Abord");
done = sharedSegment->find<bool>("Done");
}
}
// is thread really finished
std::pair<bool*, std::size_t> killed = sharedSegment->find<bool>("Killed");
mutex.first->lock();
(killed.first)[id] = true;
mutex.first->unlock();
}
MainApplication::someFunction() {
done = sharedSegment->construct<bool>("Done")[noThreads](false);
killed = sharedSegment->construct<bool>("Killed")[noThreads](false);
for (unsigned int i = 0; i < noThreads; ++i) {
// construct new threads with some parameters
new boost::thread(MyThreadClass(...));
}
while ( someCondition ){
// set every thread into working mode
mutex->lock();
for (unsigned int j = 0; j < noThreads; ++j) done[j] = false;
mutex->unlock();
// wait until every thread has finished (busy waiting again)
blockUntilThreadsFinish();
// every thread finished computation here
// change size of shared memory here
// since busy waiting is used, the shared memory will be mapped
// every second ==> grow/shrink can fail!
// if observer pattern is used, this should work, since the thread
// sleeps as long, as nothing is observed
}
mutex->lock();
(*abord) = true;
mutex->unlock();
}
我也相信我必须使用一些观察者模式来使这个100%线程安全(参见源代码中的注释)。
答案 0 :(得分:0)
删除您的shared_memory对象将分离共享内存。虽然它确实不会影响您的流程资源。