我正在使用 boost context 1.67 在 Windows 10 上创建一个具有尽可能小的堆栈大小的光纤(fcontext API)。
可能这个问题不仅特定于提升上下文,而且适用于我们使用具有最小堆栈大小的 Windows 线程的任何场景。
我在使用非常小的堆栈(低于 10kb)时遇到了问题,这些堆栈溢出异常是由 boost 上下文引发的内部堆栈展开异常引起的,如下所示:
当使用更大的堆栈(> 10 kb)时,我没有遇到任何问题。
对于复制,以下示例就足够了:
#include <memory>
#include <utility>
#include <boost/context/all.hpp>
#define STACK_SIZE 8000
struct my_allocator
{
boost::context::stack_context allocate()
{
void* memory = std::malloc(STACK_SIZE);
return {STACK_SIZE,
static_cast<char*>(memory) +
STACK_SIZE};
}
void deallocate(
boost::context::stack_context& context)
{
std::free(static_cast<char*>(context.sp) -
STACK_SIZE);
}
};
int main(int, char**)
{
boost::context::fiber fiber(
std::allocator_arg, my_allocator{},
[](boost::context::fiber&& sink) mutable {
// ...
return std::move(sink);
});
// Will cause a stack unwind exception and
// reproduces the issue
return 0;
}
Boost context 在这里仅用于执行与用户分配的堆栈的上下文切换,可能是由于 MSVC C++ 异常的一些限制引起的,这可能需要一定的最小堆栈大小才能工作。此外,SetThreadStackGuarantee
WinAPI 函数对该问题没有任何影响。
如示例所示,堆栈是通过 malloc 分配的。
使用 C++ 异常时,是否可以在 Windows 上使用小于 10kb 的堆栈?哪种情况可能导致这里的限制?