boehm-gc with C++11's thread library

1k views Asked by At

As we know, using boehm-gc in multi-thread requires calling GC_register_my_thread with stack base from GC_get_stack_base. but It seems not to work well with C++11's thread library, such as std::thread... How can I use boehm-gc with C++11's thread library?

(I use VS2013)

edit: This is tested code. std::thread is good, but std::future doesn't work (stop on _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();
}

edit: here is a capture of stack trace (Sorry that it isn't English, but I think it doesn't matter, anyway) enter image description here

and here is a debug message

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

While debugging, I found The error occurs after fu.get().

edit: The error doesn't occur with /MD(or /MDd)...

(I think GC might touch library's pointers (namespcae Concurrency), but it is just guess;;)

1

There are 1 answers

9
mockinterface On

Before you start using the collector and before you create the threads make sure that you issue both

  • GC_INIT, and
  • GC_allow_register_threads

Then in every thread follow it up with,

  • GC_get_stack_base/GC_register_my_thread, and eventually
  • GC_unregister_my_thread.

You didn't say what you are compiling with but it works for gcc 4.8 (with -std=c++11).

EDIT: The OP was able to resolve the issue by addressing the instruction above and compiling the code with the /MD[d] flags for the multi-threaded dynamic MSVCR100 runtime. The issue remained unresolved for the multithreaded statically compiled runtime.