2014-01-07 41 views
3

如我們所知,在多線程中使用boehm-gc需要調用GC_register_my_thread,堆棧庫的編號爲GC_get_stack_base。但似乎不適用於C++ 11的線程庫,如std::thread ...我如何在C++ 11的線程庫中使用boehm-gc?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併發),但它僅僅是猜測;;)

回答

1

在您開始使用採集器和創建線程之前確保你發出兩個

  • 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]標誌的代碼來解決問題。多線程靜態編譯運行時問題仍未解決。

+0

編輯:我使用VS2013 – ikh

+0

這應該沒問題,上述仍然適用。爲什麼強調C++ 11?它一直在用C++ 98(使用Visual Studio)爲你工作,現在它不?編輯: – mockinterface

+0

這是測試代碼。 std :: future不起作用; – ikh