c++ - 带有 C++11 线程库的 boehm-gc

标签 c++ c++11 boehm-gc

我们知道,在多线程中使用 boehm-gc 需要使用 GC_get_stack_base 中的堆栈基调用 GC_register_my_thread。但它似乎不能很好地与 C++11 的线程库一起使用,例如 std::thread... 我如何将 boehm-gc 与 C++11 的线程库一起使用?

(我用的是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();
}

编辑:这里是堆栈跟踪的捕获(抱歉,它不是英文的,但我认为这并不重要,无论如何) enter image description here

这是调试信息

HEAP[TestGC.exe]: Invalid address specified to RtlValidateHeap( 00E80000, 00C92F80 )

在调试的过程中,发现fu.get()之后出现了错误。

编辑:错误不会发生在/MD(或/MDd)...

(我认为 GC 可能会触及库的指针(namespcae Concurrency),但这只是猜测;;)

最佳答案

在开始使用收集器之前和创建线程之前,请确保您同时发布了

  • 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 能够通过解决上述指令并使用多线程动态 MSVCR100 运行时的 /MD[d] 标志编译代码来解决问题。对于多线程静态编译运行时,该问题仍未解决。

关于c++ - 带有 C++11 线程库的 boehm-gc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20968114/

相关文章:

c++ - 理解带有循环引用的 Shared_ptr?

c++ - 如何使用 CMake 检测编译器对 C++11 的支持

garbage-collection - 将 glib 绑定(bind)​​到 Crystal lang(GC 问题)

c - 如何将 asprintf 与 Boehm GC 一起使用?

c++ - 初始化一个本身合法的引用成员?

c++ - 如何编写指针和数据为 const 的 unique_ptr

c++ - 如何随机化排序列表?

c++ - 单字节变量的 boost::program_options

c++ - C/C++ : Automatically initialize pointers to null in visual studio

c++ - 如何将 Boost.Coroutine 与 Boehm GC 结合使用?