Boost Interprocess共享一个向量会导致奇怪的死锁(完整的代码示例)

时间:2018-04-26 08:59:45

标签: c++ multithreading boost mutex condition-variable

我使用boost::interprocess::vectorboost::interprocess::named_mutex在两个流程中共享boost::interprocess::named_condition

读者首先开始,获取互斥锁并等待写入数据。作者获得互斥体,开始写作,但它挂在更新共享向量的行

如果我运行程序,我会得到以下输出:

Reader trying to get mutex
Reader waiting for data
Writer attempting to get mutex
Writer got mutex. Number of items to write: 2
Writing value: 1

作者有两个要插入到向量中的项目,但由于某种原因,它会在插入第一个并且只是挂起后停止。

这是作者的代码(下面的完整代码):

void write(const std::vector<T>& items)
{
    std::cout << "Writer attempting to get mutex" << std::endl;

    scoped_lock<named_mutex> lock(*mutex);
    {
        std::cout << "Writer got mutex. Number of items to write: " << items.size() << std::endl;

        for(const auto& item : items)
        {
            std::cout << "Writing value: " << item << std::endl;
            vec->push_back(item);   // <--------------------------- HANGS HERE -----
        }

        std::cout << "Writer notifying reader" << std::endl;
        cond_empty->notify_all();
    }

    std::cout << "Writer finished" << std::endl;
}

这是完整的代码(应该能够复制,粘贴和运行):

#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <boost/interprocess/sync/named_condition.hpp>
#include <string>
#include <cstdlib> //std::system
#include <iostream>
#include <memory>

using namespace boost::interprocess;

template<typename T>
struct MySharedData
{
    using ShmemAllocator = allocator<T, managed_shared_memory::segment_manager>;
    using MyVector = vector<T, ShmemAllocator>;

    MySharedData(const bool isConsumer, const std::string& sharedMemoryName, const std::string& blockName, const int numBytes) : shared_memory_name(sharedMemoryName), block_name(blockName)
    {
        is_consumer = isConsumer;
        segment.reset(new managed_shared_memory(open_or_create, sharedMemoryName.c_str(), numBytes));
        const ShmemAllocator alloc_inst(segment->get_segment_manager());

        vec = segment->find_or_construct<MyVector>(blockName.c_str())(alloc_inst);
        cond_empty.reset(new named_condition(open_or_create, sharedMemoryName.c_str()));
        mutex.reset(new named_mutex(open_or_create, sharedMemoryName.c_str()));
    }

    ~MySharedData()
    {
        if(is_consumer)
        {
            segment->destroy<MyVector>(block_name.c_str());
        }
    }

    void write(const std::vector<T>& items)
    {
        std::cout << "Writer attempting to get mutex" << std::endl;

        scoped_lock<named_mutex> lock(*mutex);
        {
            std::cout << "Writer got mutex. Number of items to write: " << items.size() << std::endl;

            for(const auto& item : items)
            {
                std::cout << "Writing value: " << item << std::endl;
                vec->push_back(item);   // <--------------------------- HANGS HERE -----
            }

            std::cout << "Writer notifying reader" << std::endl;
            cond_empty->notify_all();
        }

        std::cout << "Writer finished" << std::endl;
    }

    std::vector<T> read()
    {
        std::vector<T> toReturn;

        bool continue_trying = true;

        while(continue_trying)
        {
            std::cout << "Reader trying to get mutex" << std::endl;

            scoped_lock<named_mutex> lock(*mutex);
            {
                if(nullptr != vec )
                {
                    if(vec->empty())
                    {
                        std::cout << "Reader waiting for data" << std::endl;
                        cond_empty->wait(lock);
                        std::cout << "Reader notified of data" << std::endl;
                    }

                    for(auto& t : *vec)
                    {
                        std::cout << "Reading: " << t << std::endl;
                        toReturn.push_back(t);
                    }

                    continue_trying = false;
                }
                else
                {
                    std::cout << "No data to read from shared memory: " << shared_memory_name << " block: " << block_name << std::endl;
                    continue_trying = false;
                }
            }
        }

        std::cout << "Reader finished" << std::endl;

        return toReturn;
    }

    std::unique_ptr<named_mutex>            mutex{nullptr};
    MyVector*                               vec{nullptr};
    std::unique_ptr<managed_shared_memory>  segment{nullptr};
    std::unique_ptr<named_condition>        cond_empty;
    bool                                    is_consumer{false};
    std::string                             shared_memory_name;
    std::string                             block_name;
};

void parent()
{
    MySharedData<int> msd1(false, "a", "b", 100000);
    std::vector<int> vec;
    vec.push_back(1);
    vec.push_back(2);
    msd1.write(vec);
}

void child()
{
    MySharedData<int> msd2(true, "a", "b", 100000);
    std::vector<int> x = msd2.read();
}

int main()
{
    shared_memory_object::remove("a");
    shared_memory_object::remove("b");
    shared_memory_object::remove("c");
    shared_memory_object::remove("d");
    named_mutex::remove("a");
    named_mutex::remove("b");
    named_mutex::remove("c");
    named_mutex::remove("d");
    named_condition::remove("a");
    named_condition::remove("b");
    named_condition::remove("c");
    named_condition::remove("d");

    // The below code spawns the parent method off to a separate process
    pid_t pid = fork();
    if(pid == 0)
    {
        //child();
        parent();
    }
    else if(pid > 0)
    {
        //parent();
        child();
    }

    std::cout << "FINISHED" << std::endl;
}

0 个答案:

没有答案