【问题标题】:Crash on std::thread destructor with VS CTP 14使用 VS CTP 14 在 std::thread 析构函数上崩溃
【发布时间】:2014-11-07 16:42:43
【问题描述】:

我正在使用 Visual Studio CTP 14 基于 C++11 中的标准库实现一个具有可中断线程的并发库,例如 boost 和 Java 中的那些线程。

经过一些重构后,我在 std::thread 的析构函数中遇到了崩溃(有时试图取消引用空指针,有时是“调试错误!R6010”,有时根本没有崩溃)。经过大量代码剥离以找到问题后,我无法理解问题是出在我的代码上还是可能是编译器错误。

即使在剥离代码之后,重现问题仍然需要很多东西,所以请多多包涵:)

部分线程包装器实现:

class InterruptException : public std::exception
{
public:
    const char* what() const override {return "InterruptException";}
};

class Thread
{
public:
    Thread(const Thread&) = delete;
    Thread& operator=(const Thread&) = delete;

    Thread();

    template <typename Callable>
    Thread(Callable&& action);

    Thread(Thread&& other);

    ~Thread();

    Thread& operator=(Thread&& other);

    // Sets interruption flag and call notifyAll for current condition if any.
    void interrupt();

    // Throws interrupted exception if current thread interruption flag is set.
    // This also resets the interruption flag.
    static void interruptionPoint();

    static void interruptCurrent();


    static void setCondition(std::condition_variable* cond);
    static Thread* currentThread(Thread* setter = nullptr);

private:
    std::atomic<bool>                       _interruptionFlag;
    std::atomic<std::condition_variable*>   _currentCondition;
    std::thread _stdThread;
};

template <typename Callable>
Thread::Thread(Callable&& action)
: _stdThread(),
  _interruptionFlag(false),
  _currentCondition(nullptr)
{
    _stdThread = std::thread(
        [this, runner = std::move(action)]
        {
            currentThread(this);

            try
            {
                runner();
            }
            catch (InterruptException&)
            {
                // Normal exit.
            }
            catch (...)
            {
                // Removed logging calls.
            }
        }
    );
}

Thread::~Thread()
{
    // Block at thread destruction, no detached thread support.
    if (_stdThread.joinable())
    {
        interrupt();
        _stdThread.join();
    }
}

// (More code if requested.)

(请注意,为清楚起见,上面的代码缺少部分)

我已经为 Thread 类编写了几个测试,它似乎可以正常工作。下一部分是任务运行器的精简版。

template <typename Runner>
class StrippedSystem
{
public:
    template <typename... CtorArgs>
    StrippedSystem(CtorArgs&&... args);

    StrippedSystem(const StrippedSystem&) = delete;
    StrippedSystem(StrippedSystem&&) = delete;

    // ...

private:
    template <typename... CtorArgs>
    Thread createRunnerThread(CtorArgs&&... args);

    std::mutex _mutex;
    std::condition_variable _cond;

    Thread _runner;
};

template <typename Runner>
template <typename... CtorArgs>
StrippedSystem<Runner>::StrippedSystem(CtorArgs&&... args)
{
    _runner = createRunnerThread(std::forward<CtorArgs>(args)...);
}

template <typename Runner>
template <typename... CtorArgs>
Thread StrippedSystem<Runner>::createRunnerThread(CtorArgs&&... args)
{
    auto runnerProc =
    [&]
    {
        Thread::setCondition(&_cond);

        try
        {
            std::unique_lock<std::mutex> lock(_mutex);
            _cond.wait(
                lock,
                [&]
                {
                    Thread::interruptionPoint();
                    return false;
                }
            );
        }
        catch (...)
        {
            Thread::setCondition(nullptr);
            std::rethrow_exception(std::current_exception());
        }
    };

    return Thread(runnerProc);
}

精简后的 StrippedSystem 的代码非常简单。它创建一个等待直到中断的线程。当调用 Thread 的析构函数时,会设置中断标志并通知条件。然后线程运行到一个中断点(在 _cond.wait lambda 内部),该中断点抛出一个被线程包装器捕获的 InterruptionException 并且线程正常退出。

现在是让一切崩溃的代码:

struct ConstructedRunner
{
    ConstructedRunner(int a, std::string b)
    : i(a), j(b)
    {
    }

    int i;
    std::string j;
};

int main(int argc, char* argv[])
{
    {
        StrippedSystem<ConstructedRunner> testSys2(1, "foobar");
    }

    return 0;
}

如上所述,崩溃可能是“调试错误!已调用中止”、访问冲突(试图取消引用空指针)或在某些情况下根本没有崩溃。

经过一些故障排除后,我发现以下不会崩溃

struct DummyRunner
{
};

int main(int argc, char* argv[])
{
    {
        StrippedSystem<DummyRunner> testSys1;
    }

    return 0;
}

经过更多故障排除后,我发现在系统构造函数替换

_runner = createRunnerThread(std::forward<CtorArgs>(args)...);

_runner = Thread(
        [&]
        {
            Thread::setCondition(&_cond);

            try
            {
                std::unique_lock<std::mutex> lock(_mutex);
                _cond.wait(
                    lock,
                    [&]
                    {
                        Thread::interruptionPoint();
                        return false;
                    }
                );
            }
            catch (...)
            {
                Thread::setCondition(nullptr);
                std::rethrow_exception(std::current_exception());
            }
        }
    );

还修复了崩溃。 即使没有使用转发的参数。

这对我来说毫无意义,因为运行的代码应该是相同的。这是编译器问题还是我做错了什么导致了一些奇怪的并发问题?

使用 Visual Studio CTP 14 for Windows 7 在调试模式下构建。

【问题讨论】:

  • Thread 模板构造函数中捕获 std::move(action) 而不是 std::forward&lt;Callable&gt;(action) 是可疑的。
  • @Casey 现在用std::forward&lt;Callable&gt; 尝试,没有变化。

标签: c++ multithreading visual-studio c++14


【解决方案1】:

经过一些帮助,我解决了错误。

问题在于currentThread(this) 位于Thread 模板构造函数中。该函数将线程指针设置为线程局部静态变量,稍后读取该变量以获取中断标志和当前条件(如果有)。问题是this 指针指向一个临时对象。这可以在_runner = Thread(...) 中看到,其中临时Thread 对象位于右侧,并被设置为线程本地数据。线程移动后数据未更新。

Thread 的析构函数中,interrupt 检查了线程本地标志,这就是析构函数崩溃的原因。

【讨论】:

    猜你喜欢
    • 2013-03-14
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    • 1970-01-01
    • 2014-11-12
    • 2020-02-13
    • 2015-12-17
    相关资源
    最近更新 更多