使用VS CTP 14在std :: thread析构函数上崩溃

时间:2014-09-13 18:27:00

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

我使用Visual Studio CTP 14实现了一个带有可中断线程的并发库,比如基于C ++ 11中标准库的boost和Java中的可中断线程。

经过一些重构后,我在std :: thread的析构函数中遇到了崩溃(有时试图取消引用空指针,有时候" Debug Error!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;
}

如上所述,崩溃可能是&#34;调试错误! abort已被调用&#34;,访问冲突(试图取消引用空指针)或在某些情况下根本没有崩溃。

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

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());
            }
        }
    );

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

这对我来说没有意义,因为运行的代码应该是相同的。这是一个编译器问题还是我做了一些非常错误的事情导致了一些奇怪的并发问题?

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

1 个答案:

答案 0 :(得分:0)

经过一些帮助后,我得到了错误。

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

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