boost::interprocess::managed_shared_memory
プロセス間通信に使用しています。拡大/縮小するには、共有メモリを使用するすべてのプロセスで共有メモリのマッピングを解除する必要があります。2 つのスレッドがある場合、これはどのように行われますか?
ドキュメントを検索した限り、これ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% スレッド セーフを実現するには、なんらかのオブザーバー パターンを使用する必要があると考えています (ソース コードのコメントを参照してください)。