请问:c++11 用成员函数创建多线程传递参数的有关问题

请教:c++11 用成员函数创建多线程传递参数的问题
本帖最后由 tj807126663 于 2014-05-29 17:19:12 编辑
在调试http://www.cplusplus.com/reference/thread/thread/thread/的示例程序的时候一直报错,如果将调用函数修改成无参数类型的话,程序是可以成功编译并运行的,请朋友们帮我看一下问题在哪里?
精简后的代码如下:
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector

struct C : std::atomic<int> {
  C() : std::atomic<int>(0) {}
  void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};

int main ()
{
  std::vector<std::thread> threads;

  std::cout << "increase counter (bar) with 10 threads using member...\n";
  C bar;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread(&C::increase_member,std::ref(bar),1000));

  std::cout << "synchronizing all threads...\n";
  for (auto& th : threads) th.join();

  std::cout << "bar: " << bar << '\n';

  return 0;
}

错误提示如下:
In file included from /usr/include/c++/4.8/thread:39:0,
                 from example.cpp:3:
/usr/include/c++/4.8/functional: In instantiation of ‘struct std::_Bind_simple<std::_Mem_fn<void (C::*)(int)>(std::reference_wrapper<C>, int)>’:
/usr/include/c++/4.8/thread:137:47:   required from ‘std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (C::*)(int); _Args = {std::reference_wrapper<C>, int}]’
example.cpp:18:73:   required from here
/usr/include/c++/4.8/functional:1697:61: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (C::*)(int)>(std::reference_wrapper<C>, int)>’
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
/usr/include/c++/4.8/functional:1727:9: error: no type named ‘type’ in ‘class std::result_of<std::_Mem_fn<void (C::*)(int)>(std::reference_wrapper<C>, int)>’
         _M_invoke(_Index_tuple<_Indices...>)
         ^


------解决方案--------------------
勘误:
引用:
目前,你可以用传指针的方式:
std::thread(&C::increase_member, &bar, 1000) // 去掉一个多余的“)”

或者用std::bind、lambda等解决。

------解决方案--------------------
lamda
#include <iostream>       // std::cout
#include <atomic>         // std::atomic
#include <thread>         // std::thread
#include <vector>         // std::vector
 
struct C : std::atomic<int> {
  C() : std::atomic<int>(0) {}
  void increase_member (int n) { for (int i=0; i<n; ++i) fetch_add(1); }
};
 
int main ()
{
  std::vector<std::thread> threads;
 
  std::cout << "increase counter (bar) with 10 threads using member...\n";
  C bar;
  for (int i=1; i<=10; ++i)
    threads.push_back(std::thread([&bar](){bar.increase_member(1000);}));
 
  std::cout << "synchronizing all threads...\n";
  for (auto& th : threads) th.join();
 
  std::cout << "bar: " << bar << '\n';
 
  return 0;
}