【问题标题】:C++0x: thread, gcc or my error?C++0x:线程、gcc 还是我的错误?
【发布时间】:2011-09-09 09:24:26
【问题描述】:

是 GCC 4.7.0 还是我?我做错了什么?

这会引发std::system_error “不允许操作” 异常:

struct DumbFib {
    size_t operator()(size_t n) { return fib(n); }
    static size_t fib(size_t n) {
        return n<2 ? 1 : fib(n-2)+fib(n-1);
    }
};

void sample() {
    DumbFib dumbfib;
    thread th{ dumbfib, 35 };    // <- system_error!
    th.join();
};

虽然这有效:

void work(size_t loop) {
    for(int l = loop; l>0; --l) {
        for(int i = 1000*1000; i>0; --i)
            ;
        cerr << l << "...";
    }
    cerr << endl;
}

int main() {
    //sample();
    thread t { work, 100 };     // <- fine
    t.join();
}

当然,区别在于:

  • 不工作的代码使用了 Functor(带有operator() 的类)
  • 工作代码使用函数指针。

我在某处使用了错误的函子吗?我看不到在哪里,是吗?是否暗示gdb 的堆栈中有这个:

#7  ... in std::thread::_M_start_thread (..., __b=warning: RTTI symbol not found\
  for class 'std::_Sp_counted_ptr_inplace<std::thread::_Impl<std::\
  _Bind_simple<DumbFib()(int)> >, ..., (__gnu_cxx::_Lock_policy)2>

注意:我也试过了

  • 首先初始化DumbFib,给它一个成员变量n_=35,结果相同。
  • 直接使用thread th{ DumbFib, 35 };thread th{ DumbFib{}, 35 }; 给函子

【问题讨论】:

  • 你在什么系统上运行这个?
  • linux 64bit (ubuntu 10.4 LTS), gcc-4.7.0, svn checkout 从上周开始。

标签: multithreading c++11 gcc4


【解决方案1】:

使用g++ 编译代码时,请使用-pthread 选项。

【讨论】:

  • 多么尴尬.. 我曾经犯过这个错误,并认为我已经纠正了。我没有。所以,现在它起作用了!太好了!
【解决方案2】:

我也遇到了类似的问题,感谢 Jason,它解决了我的问题

确切的选项将是

g++ code.cpp -lpthread -std=c++0x

这就是我在 g++ 4.6.3 版上要做的事情

【讨论】:

    猜你喜欢
    • 2011-05-21
    • 2011-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    相关资源
    最近更新 更多