如我们所知,在多线程中使用boehm-gc需要从GC_register_my_thread调用具有堆栈基的GC_get_stack_base。但是它似乎不能很好地与C++11的线程库,如std::thread.如何在C++11的线程库中使用boehm-gc?
(我使用VS2013)
编辑:这是测试代码。std::thread很好,但是std::future不起作用(停止在_CrtIsValidHeapPointer上
#include <iostream>
#include <thread>
#include <future>
#define GC_THREADS
#include <gc.h>
#include <gc_cpp.h>
#pragma comment(lib, "gcmt-lib")
void foo()
{
GC_stack_base sb;
GC_get_stack_base(&sb);
GC_register_my_thread(&sb);
int *ptr;
for (int i = 0; i < 10; i++)
{
ptr = new (GC) int;
*ptr = 1;
}
GC_unregister_my_thread();
}
int main()
{
GC_INIT();
GC_allow_register_threads();
std::cout << "test for std::thread";
std::thread thrd(foo);
thrd.join();
std::cout << " [sucs]\n";
std::cout << "test for std::future";
std::future<void> fu = std::async(std::launch::async, foo);
fu.get();
std::cout << " [sucs]\n";
std::cin.get();
}编辑:下面是堆栈跟踪的捕获(抱歉,它不是英语,但我认为这并不重要)

下面是一条调试消息
HEAP[TestGC.exe]: Invalid address specified to RtlValidateHeap( 00E80000, 00C92F80 )在调试过程中,我发现错误发生在fu.get()之后。
编辑:错误不发生在/MD(或/MDd).
(我认为GC可能会触及库的指针(命名为并发),但只是猜测;;)
发布于 2014-01-09 08:06:15
在开始使用收集器之前和创建线程之前,请确保同时发出这两个命令。
GC_INIT,和GC_allow_register_threads在每一条线索中,
GC_get_stack_base/GC_register_my_thread,最终GC_unregister_my_thread。您没有说明您正在编译的内容,但它适用于gcc 4.8 (使用-std=c++11)。
编辑: OP解决了这个问题,解决了上面的指令,并为多线程动态/MD[d]运行时编译了带有MSVCR100标志的代码。对于多线程静态编译运行时,该问题仍未解决。
https://stackoverflow.com/questions/20968114
复制相似问题