【问题标题】:What is wrong with the mutexes in this attempt at a `std::future` implementation for C++03?在 C++03 的“std::future”实现中,互斥锁有什么问题?
【发布时间】:2014-04-14 17:33:34
【问题描述】:

我正在尝试调整 Martinho Fernandes's sample std::future implementation 以便它可以在带有 Boost 1.40 的 C++03 下运行,作为一种廉价的权宜之计,直到我可以访问 Boost 1.41 或 C++11 本身。

我的改编并不漂亮,当然也不是最佳的,但我宁愿希望它至少能奏效。但是,在 gcc 版本 4.4.1 20090725 (Red Hat 4.4.1-2) 下,它没有。

这里是futures.h

#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <stdexcept>

template <typename T>
class future;

template <typename T>
class promise;

namespace detail {

    template <typename T>
    struct future_shared_state
    {
    public:

        void wait(boost::mutex& m) const
        {
            boost::mutex::scoped_lock lock(m, boost::adopt_lock);
            while (!(state || error))
                available.wait(lock);
        }

        T& get()
        {
            if (state)
                return *state;

            if (error)
                throw *error;

            throw std::runtime_error("WTF");
        }

        template <typename U>
        void set_value(const U& value)
        {
            state = value;
            available.notify_all();
        }

        void set_exception(boost::shared_ptr<std::exception> e)
        {
            error = e;
            available.notify_all();
        }

    private:
        mutable boost::condition_variable available;
        boost::optional<T> state;
        boost::shared_ptr<std::exception> error;

        friend class promise<T>;
        friend class future<T>;
        mutable boost::mutex m;
    };

}

template <typename T>
struct future
{
public:
    future() {}
    ~future() {}

    T get()
    {
        boost::shared_ptr<detail::future_shared_state<T> > old_box;
        swap(box, old_box);

        boost::mutex::scoped_lock lock(old_box->m);
        old_box->wait(old_box->m);
        return old_box->get();
    }

    bool valid() const
    {
        return !!box;
    }

    void wait() const
    {
        boost::mutex::scoped_lock lock(box->m);
        box->wait(box->m);
    }

private:
    boost::shared_ptr<detail::future_shared_state<T> > box;

    friend class promise<T>;
    future(boost::shared_ptr<detail::future_shared_state<T> > const& box) : box(box) {}
};

template <typename T>
struct promise
{
public:
    promise() : box(new detail::future_shared_state<T>) {}
    ~promise() {}   

    void swap(promise& other)
    {
        box.swap(other.box);
    }

    future<T> get_future()
    {
        return future<T>(box);
    }

    void set_value(T const& value)
    {
        box->set_value(value);
    }

    void set_exception(boost::shared_ptr<std::exception> e)
    {
        box->set_exception(e);
    }

private:
    boost::shared_ptr<detail::future_shared_state<T> > box;
};

template<typename T>
void swap(promise<T>& lhs, promise<T>& rhs)
{
    lhs.swap(rhs);
}

以及执行:

#include "futures.h"
#include <iostream>
#include <boost/thread.hpp>

void foo(promise<unsigned int> p)
{
    sleep(1);
    p.set_value(42);
}

int main()
{
    promise<unsigned int> p;
    future <unsigned int> f(p.get_future());

    boost::thread t(&foo, p);
    std::cout << f.get() << std::endl;

    t.join();
}

// g++ -O0 -g test.cpp -lboost_thread -pthread -o test

结果始终如下:

42
test: /usr/local/include/boost/thread/pthread/mutex.hpp:45: boost::mutex::~mutex(): Assertion `!pthread_mutex_destroy(&m)' failed.
Aborted

来自 gdb 的回溯:

#0  0x00679422 in __kernel_vsyscall ()
#1  0x002ac781 in *__GI_raise (sig=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:64
#2  0x002ae04a in *__GI_abort () at abort.c:88
#3  0x002a58de in *__GI___assert_fail (assertion=0x805de56 "!pthread_mutex_destroy(&m)",
    file=0x805de24 "/usr/local/include/boost/thread/pthread/mutex.hpp", line=45, function=0x805e071 "boost::mutex::~mutex()")
    at assert.c:78
#4  0x0804bdd5 in boost::mutex::~mutex (this=0x806c9c0, __in_chrg=<value optimized out>)
    at /usr/local/include/boost/thread/pthread/mutex.hpp:45
#5  0x0804d020 in detail::future_shared_state<unsigned int>::~future_shared_state (this=0x806c980,
    __in_chrg=<value optimized out>) at futures.h:35
#6  0x0804d099 in boost::checked_delete<detail::future_shared_state<unsigned int> > (x=0x806c980)
    at /usr/local/include/boost/checked_delete.hpp:34
#7  0x0804d69c in boost::detail::sp_counted_impl_p<detail::future_shared_state<unsigned int> >::dispose (this=0x806c9e0)
    at /usr/local/include/boost/smart_ptr/detail/sp_counted_impl.hpp:78
#8  0x0804bb68 in boost::detail::sp_counted_base::release (this=0x806c9e0)
    at /usr/local/include/boost/smart_ptr/detail/sp_counted_base_gcc_x86.hpp:145
#9  0x0804bbfe in boost::detail::shared_count::~shared_count (this=0xbffff634, __in_chrg=<value optimized out>)
    at /usr/local/include/boost/smart_ptr/detail/shared_count.hpp:217
#10 0x0804c2d4 in boost::shared_ptr<detail::future_shared_state<unsigned int> >::~shared_ptr (this=0xbffff630,
    __in_chrg=<value optimized out>) at /usr/local/include/boost/smart_ptr/shared_ptr.hpp:169
#11 0x0804c535 in promise<unsigned int>::~promise (this=0xbffff630, __in_chrg=<value optimized out>) at futures.h:125
#12 0x0804b937 in main () at test.cpp:19

除了糟糕的风格,我的互斥锁有什么问题?

【问题讨论】:

  • 您在哪个操作系统上运行?
  • 您使用的是哪个版本的 g++?我无法使用 4.5 进行复制。
  • 另外,test.cpp 中第 47 行的错误表明您的 main.cpp 中的行数比显示的行数多。您能否指出终止发生在 main.cpp 中的哪一行?我在join 之后猜测,但我宁愿不猜测。
  • @Joachim Isaksson 即使没有看到代码,我也敢打赌这是main 的结束},导致析构函数被调用。
  • @JoachimIsaksson 是的,我认为 Mark 是对的。这是一个逐字记录的最小测试用例(尽管我从不 100% 排除发布过程中的错误!)

标签: c++ boost boost-thread future c++03


【解决方案1】:

future_shared_state::valuefuture_shared_state::errorset_valueset_exception 上存在数据竞争,而无需获取 wait 用来保护它们的互斥体即可访问它们。

您遇到的实际问题是由于您在future_shared_state::wait 的调用者中使用了boost::mutex::scoped_lock:您成功地避免了在future_shared_state::wait 内使用adopt_lock 锁定互斥锁两次,但是scoped_lock 的两个析构函数运行并解锁互斥锁两次。

通过将锁定全部设置在future_shared_state (Demo at Coliru) 内部,这两个问题都可以轻松解决:

namespace detail {

    template <typename T>
    struct future_shared_state
    {
    public:

        void wait() const
        {
            boost::mutex::scoped_lock lock(m);
            while (!(state || error))
                available.wait(lock);
        }

        T& get()
        {
            if (state)
                return *state;

            if (error)
                throw *error;

            throw std::runtime_error("WTF");
        }

        template <typename U>
        void set_value(const U& value)
        {
            {
                boost::mutex::scoped_lock lock(m);
                state = value;
            }
            available.notify_all();
        }

        void set_exception(boost::shared_ptr<std::exception> e)
        {
            {
                boost::mutex::scoped_lock lock(m);
                error = e;
            }
            available.notify_all();
        }

    private:
        mutable boost::condition_variable available;
        boost::optional<T> state;
        boost::shared_ptr<std::exception> error;

        mutable boost::mutex m;
    };

}

template <typename T>
class promise;

template <typename T>
struct future
{
public:
    future() {}
    ~future() {}

    T get()
    {
        boost::shared_ptr<detail::future_shared_state<T> > old_box;
        swap(box, old_box);

        old_box->wait();
        return old_box->get();
    }

    bool valid() const
    {
        return !!box;
    }

    void wait() const
    {
        box->wait();
    }

private:
    boost::shared_ptr<detail::future_shared_state<T> > box;

    friend class promise<T>;
    future(boost::shared_ptr<detail::future_shared_state<T> > const& box) : box(box) {}
};

template <typename T>
struct promise
{
public:
    promise() : box(new detail::future_shared_state<T>) {}
    ~promise() {}   

    void swap(promise& other)
    {
        box.swap(other.box);
    }

    future<T> get_future()
    {
        return future<T>(box);
    }

    void set_value(T const& value)
    {
        box->set_value(value);
    }

    void set_exception(boost::shared_ptr<std::exception> e)
    {
        box->set_exception(e);
    }

private:
    boost::shared_ptr<detail::future_shared_state<T> > box;
};

【讨论】:

  • 纯风格问题:我会公开其他 future 构造函数并摆脱 promise 的朋友和前向声明。
  • 有道理;我认为原始代码是这样的,因此可以设置替代锁(定时锁等等)。
  • 谢谢@Casey;这现在有效,我明白为什么。
猜你喜欢
  • 2023-03-22
  • 1970-01-01
  • 2014-09-26
  • 2021-06-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
  • 2011-08-05
相关资源
最近更新 更多