我正在使用带有默认优化设置(/ O2)的VS2012,此问题仅存在于发布模式中.
我有一些代码使用michael_deque(使用标准GC)和指向(抽象)类型的指针T.
当我尝试将指针推回到派生自的类型时,T应用程序在退出push_back()函数时崩溃michael_deque.
问题似乎完全取决于这种特定类型T,因为编写一个虚拟类foo,在类中派生它bar(并在构造函数中打印一些东西以避免它被优化掉),然后再推回到new bar()michael_deque不会导致崩溃.
T有问题的课程是这样的:
class Task
{
public:
Task() : started(false), unfinishedTasks(1), taskID(++taskIDCounter) {};
Task(unsigned int parentID_) : started(false), unfinishedTasks(1), taskID(++taskIDCounter), parentID(parentID_)/*, taken(0)*/ {};
virtual ~Task() = 0 {};
virtual void execute() final
{
this->doActualWork();
unfinishedTasks--;
}
virtual void doActualWork() = 0;
public:
unsigned int taskID; //ID of this task
unsigned int parentID; //ID of the parent of this task
bool started;
std::atomic<unsigned int> unfinishedTasks; //Number of child tasks that are still unfinished
std::vector<unsigned int> dependencies; //list of IDs of all tasks that this task depends on
};
Run Code Online (Sandbox Code Playgroud)
错误可以在最小程序中重现(如果您碰巧有一个可以像我一样执行此操作的环境,只需放置一个std::atomic<unsigned int> taskIDCounterTask类可以看到它的地方):
#include <cds/container/michael_deque.h>
#include "task.hpp"
class a : public Task
{
a()
{
std::cout<<"dummy print"<<std::endl;
}
virtual ~a()
{
}
virtual void doActualWork()
{
std::cout<<"whatever"<<std::endl;
}
};
int main()
{
cds::Initialize();
{
cds::gc::HP hpGC;
cds::gc::HP::thread_gc myThreadGC;
cds::container::MichaelDeque<cds::gc::HP,Task*> tasks;
tasks.push_back(new a()); //will crash at the end of push_back
}
cds::Terminate();
}
Run Code Online (Sandbox Code Playgroud)
可能是什么原因造成的?我是否在类Task中做了一些未定义的事情,这会导致优化问题出现问题?
这确实是一个编译器错误.更具体地说,它是与Visual Studio 2012的原子实现相关的错误.
std :: atomic类的一些模板特化修改堆栈帧指针(ebp)而不备份它并在修改之前/之后从堆栈弹出它.libcds库使用这些特化之一,并且在函数范围之外运行时,生成的错误帧指针有时会导致非法内存访问(未定义的行为似乎可以防止调试模式中的灾难性故障).
这个特殊情况下的修复是使libcds使用不同的原子库,然后是Visual Studio提供的标准库.库决定在cxx11_atomic.h中使用哪个实现:
#if defined(CDS_USE_BOOST_ATOMIC)
# error "Boost.atomic is not supported"
//# include <boost/version.hpp>
//# if BOOST_VERSION >= 105300
//# include <boost/atomic.hpp>
//# define CDS_ATOMIC boost
//# define CDS_CXX11_ATOMIC_BEGIN_NAMESPACE namespace boost {
//# define CDS_CXX11_ATOMIC_END_NAMESPACE }
//# else
//# error "Boost version 1.53 or above is needed for boost.atomic"
//# endif
#elif CDS_CXX11_ATOMIC_SUPPORT == 1
// Compiler supports C++11 atomic (conditionally defined in cds/details/defs.h)
# include <cds/compiler/cxx11_atomic_prepatches.h>
# include <atomic>
# define CDS_ATOMIC std
# define CDS_CXX11_ATOMIC_BEGIN_NAMESPACE namespace std {
# define CDS_CXX11_ATOMIC_END_NAMESPACE }
# include <cds/compiler/cxx11_atomic_patches.h>
#else
# include <cds/compiler/cxx11_atomic.h>
# define CDS_ATOMIC cds::cxx11_atomics
# define CDS_CXX11_ATOMIC_BEGIN_NAMESPACE namespace cds { namespace cxx11_atomics {
# define CDS_CXX11_ATOMIC_END_NAMESPACE }}
#endif
Run Code Online (Sandbox Code Playgroud)
if语句的第二个分支可以更改为类似的
#elif CDS_CXX11_ATOMIC_SUPPORT == 255
Run Code Online (Sandbox Code Playgroud)
这将导致库始终使用自己的原子实现.