0

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% 线程安全(参见源代码中的注释)。

4

1 回答 1

0

删除 shared_memory 对象将分离共享内存。尽管它确实不会影响您的流程资源。

于 2012-12-11T16:12:35.280 回答