0
나는 프로세스 간 통신을 위해 boost::interprocess::managed_shared_memory
을 사용하고 있습니다. 확장/축소를 위해서는 공유 메모리가이를 사용하는 모든 프로세스에서 매핑 해제되어야합니다. 두 개의 스레드가 있다고 가정하면 어떻게됩니까?boost :: interprocess에서 공유 메모리의 매핑을 올바르게 해제하는 방법은 무엇입니까?
필자가 boost
설명서를 검색 한 경우 unmap/detach 기능과 같은 것이 없으므로 포인터를 삭제해야 할 수도 있습니다. 나는 또한 내가 (소스 코드에 주석을 참조)이 100 % 스레드 안전하기 위해 일부 관찰자 패턴을 사용할 필요가 있다고 생각
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();
}
(컴파일 안된 /하지 않음) :이 작동합니다.